2 import pyarrow.dataset as ds
3 import pyarrow.parquet as pq
4 from itertools import groupby, islice, chain
6 from collections import Counter
11 from nltk import wordpunct_tokenize, MWETokenizer, sent_tokenize
12 from nltk.corpus import stopwords
13 from nltk.util import ngrams
15 from random import random
18 # taken from https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url
19 urlregex = re.compile(r"[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)")
21 # compute term frequencies for comments in each subreddit by week
22 def weekly_tf(partition, mwe_pass = 'first'):
23 dataset = ds.dataset(f'/gscratch/comdata/output/reddit_comments_by_subreddit.parquet/{partition}', format='parquet')
25 if not os.path.exists("/gscratch/comdata/users/nathante/reddit_comment_ngrams_10p_sample/"):
26 os.mkdir("/gscratch/comdata/users/nathante/reddit_comment_ngrams_10p_sample/")
28 if not os.path.exists("/gscratch/comdata/users/nathante/reddit_tfidf_test_authors.parquet_temp/"):
29 os.mkdir("/gscratch/comdata/users/nathante/reddit_tfidf_test_authors.parquet_temp/")
31 ngram_output = partition.replace("parquet","txt")
33 if os.path.exists(f"/gscratch/comdata/users/nathante/reddit_comment_ngrams_10p_sample/{ngram_output}"):
34 os.remove(f"/gscratch/comdata/users/nathante/reddit_comment_ngrams_10p_sample/{ngram_output}")
36 batches = dataset.to_batches(columns=['CreatedAt','subreddit','body','author'])
38 schema = pa.schema([pa.field('subreddit', pa.string(), nullable=False),
39 pa.field('term', pa.string(), nullable=False),
40 pa.field('week', pa.date32(), nullable=False),
41 pa.field('tf', pa.int64(), nullable=False)]
44 author_schema = pa.schema([pa.field('subreddit', pa.string(), nullable=False),
45 pa.field('author', pa.string(), nullable=False),
46 pa.field('week', pa.date32(), nullable=False),
47 pa.field('tf', pa.int64(), nullable=False)]
50 dfs = (b.to_pandas() for b in batches)
53 df['week'] = (df.CreatedAt - pd.to_timedelta(df.CreatedAt.dt.dayofweek, unit='d')).dt.date
56 dfs = (add_week(df) for df in dfs)
58 def iterate_rows(dfs):
60 for row in df.itertuples():
63 rows = iterate_rows(dfs)
65 subreddit_weeks = groupby(rows, lambda r: (r.subreddit, r.week))
67 if mwe_pass != 'first':
68 mwe_dataset = ds.dataset(f'/gscratch/comdata/users/nathante/reddit_comment_ngrams_pwmi.parquet',format='parquet')
69 mwe_dataset = mwe_dataset.to_pandas(columns=['phrase','phraseCount','phrasePWMI'])
70 mwe_dataset = mwe_dataset.sort_values(['phrasePWMI'],ascending=False)
71 mwe_phrases = list(mwe_dataset.phrase[0:1000])
74 mwe_tokenize = MWETokenizer(mwe_phrases).tokenize
77 def remove_punct(sentence):
79 for token in sentence:
82 if c not in string.punctuation:
84 if len(new_token) > 0:
85 new_sentence.append(new_token)
89 stopWords = set(stopwords.words('english'))
91 # we follow the approach described in datta, phelan, adar 2017
92 def my_tokenizer(text):
93 # remove stopwords, punctuation, urls, lower case
98 text = urlregex.sub("", text)
101 sentences = sent_tokenize(text)
104 sentences = map(wordpunct_tokenize, sentences)
108 sentences = map(remove_punct, sentences)
110 # remove sentences with less than 2 words
111 sentences = filter(lambda sentence: len(sentence) > 2, sentences)
113 # datta et al. select relatively common phrases from the reddit corpus, but they don't really explain how. We'll try that in a second phase.
114 # they say that the extract 1-4 grams from 10% of the sentences and then find phrases that appear often relative to the original terms
115 # here we take a 10 percent sample of sentences
116 if mwe_pass == 'first':
117 sentences = list(sentences)
118 for sentence in sentences:
120 grams = list(chain(*map(lambda i : ngrams(sentence,i),range(4))))
121 with open(f'/gscratch/comdata/users/nathante/reddit_comment_ngrams_10p_sample/{ngram_output}','a') as gram_file:
123 gram_file.write(' '.join(ng) + '\n')
124 for token in sentence:
125 if token not in stopWords:
130 sentences = map(mwe_tokenize, sentences)
131 sentences = map(lambda s: filter(lambda token: token not in stopWords, s), sentences)
132 return chain(* sentences)
134 def tf_comments(subreddit_weeks):
135 for key, posts in subreddit_weeks:
136 subreddit, week = key
138 authors = Counter([])
140 tokens = my_tokenizer(post.body)
142 authors.update([post.author])
144 for term, tf in tfs.items():
145 yield [True, subreddit, term, week, tf]
147 for author, tf in authors.items():
148 yield [False, subreddit, author, week, tf]
150 outrows = tf_comments(subreddit_weeks)
154 with pq.ParquetWriter(f"/gscratch/comdata/users/nathante/reddit_tfidf_test.parquet_temp/{partition}",schema=schema,compression='snappy',flavor='spark') as writer, pq.ParquetWriter(f"/gscratch/comdata/users/nathante/reddit_tfidf_test_authors.parquet_temp/{partition}",schema=author_schema,compression='snappy',flavor='spark') as author_writer:
156 chunk = islice(outrows,outchunksize)
157 pddf = pd.DataFrame(chunk, columns=["is_token"] + schema.names)
159 author_pddf = pddf.loc[pddf.is_token == False, schema.names]
160 pddf = pddf.loc[pddf.is_token == True, schema.names]
162 author_pddf = author_pddf.rename({'term':'author'}, axis='columns')
163 author_pddf = author_pddf.loc[:,author_schema.names]
165 table = pa.Table.from_pandas(pddf,schema=schema)
166 author_table = pa.Table.from_pandas(author_pddf,schema=author_schema)
167 if table.shape[0] == 0:
169 writer.write_table(table)
170 author_writer.write_table(author_table)
173 author_writer.close()
177 files = os.listdir("/gscratch/comdata/output/reddit_comments_by_subreddit.parquet/")
178 with open("tf_task_list",'w') as outfile:
180 if f.endswith(".parquet"):
181 outfile.write(f"python3 tf_comments.py weekly_tf {f}\n")
183 if __name__ == "__main__":
184 fire.Fire({"gen_task_list":gen_task_list,
185 "weekly_tf":weekly_tf})