reddit-title-body / extraction_script /extract_title_selftext.py
nreimers's picture
add README
605a1ad
raw
history blame
1.24 kB
import json
import gzip
import sys
import re
import tqdm
from collections import defaultdict
import logging
def clean_text(text):
text = text.strip()
text = re.sub(r'\[(.*)\]\(.*\)', '\g<1>', text) #Markdown
text = re.sub(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', '', text) # URLs
return text
for line in tqdm.tqdm(sys.stdin):
try:
data = json.loads(line)
if 'title' in data and 'selftext' in data and 'num_comments' in data:
title = clean_text(data['title'])
selftext = clean_text(data['selftext'])
num_comments = data['num_comments']
score = data['score']
subreddit = data['subreddit'] if 'subreddit' in data else ''
if 'upvote_ratio' in data and float(data['upvote_ratio']) < 0.5:
continue
if len(title) > 25 and len(title)+25 < len(selftext) < 4096 and (score >= 3 or num_comments >= 3):
print(json.dumps({'title': title, 'body': selftext, 'subreddit': subreddit}))
except:
logging.warning("exception")