"""Feature extraction shared by train.py and predict.py.""" import json, os, re, math import numpy as np import emoji from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer HERE = os.path.dirname(os.path.abspath(__file__)) _VADER = SentimentIntensityAnalyzer() _NRC = json.load(open(os.path.join(HERE, 'nrc_emotion_lexicon.json'))) EMOTIONS = ["anger", "anticipation", "disgust", "fear", "joy", "sadness", "surprise", "trust"] URL_RE = re.compile(r'https?://\S+') TCO_RE = re.compile(r'https?://t\.co/\S+') HASH_RE = re.compile(r'(?= 2), n_numbers=len(NUM_RE.findall(t)), n_emojis=emoji.emoji_count(t), n_hashtags=len(HASH_RE.findall(t)), n_mentions=len(MENT_RE.findall(t)), n_links=len(URL_RE.findall(t)) if n_links is None else n_links, starts_with_mention=int(t.strip().startswith('@')), vader_compound=vs['compound'], vader_pos=vs['pos'], vader_neg=vs['neg'], vader_neu=vs['neu'], sentiment_abs=abs(vs['compound']), ) for e in EMOTIONS: f[f'emo_{e}'] = emo[e] / nw f['emo_total'] = sum(emo.values()) / nw return f def post_features(has_photo=0, has_video=0, is_reply=0, is_quote=0, hour_utc=None, weekday=None): import datetime as dt now = dt.datetime.now(dt.timezone.utc) h = now.hour if hour_utc is None else hour_utc wd = now.weekday() if weekday is None else weekday return dict(has_media=int(bool(has_photo or has_video)), has_photo=int(bool(has_photo)), has_video=int(bool(has_video)), is_reply=int(bool(is_reply)), is_quote=int(bool(is_quote)), hour_utc_sin=math.sin(2 * math.pi * h / 24), hour_utc_cos=math.cos(2 * math.pi * h / 24), is_weekend=int(wd >= 5)) def author_features(followers, verified=0): return dict(log_followers=math.log10(1 + max(followers, 0)), verified=int(bool(verified)))