#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015 Doris Hoogeveen (doris dot hoogeveen at gmail)
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os, re, sys
import nltk, json, codecs
import pydoc, math
import zipfile, random, datetime
import itertools
from operator import truediv
from scipy.misc import comb
from random import randrange
from HTMLParser import HTMLParser
# Written by Doris Hoogeveen Nov 2015. For a usage please call the script without arguments.
def load_subforum(subforumzipped):
''' Takes a subforum.zip file as input and returns a StackExchange Subforum class object.'''
return Subforum(subforumzipped)
class Subforum():
def __init__(self, zipped_catfile):
''' This class takes a StackExchange subforum.zip file as input and makes it queryable via the methods below. '''
# Check to see if supplied file exists and is a valid zip file.
if not os.path.exists(zipped_catfile):
sys.exit('The supplied zipfile does not exist. Please supply a valid StackExchange subforum.zip file.')
if not zipfile.is_zipfile(zipped_catfile):
sys.exit('Please supply a valid StackExchange subforum.zip file.')
self.cat = os.path.basename(zipped_catfile).split('.')[0]
self._unzip_and_load(zipped_catfile)
# Stopwords for cleaning. They need to be initialised here in case someone accesses self.stopwords.
self.__indri_stopwords = ['a', 'about', 'above', 'according', 'across', 'after', 'afterwards', 'again', 'against', 'albeit', 'all', 'almost', 'alone', 'along', 'already', 'also', 'although', 'always', 'am', 'among', 'amongst', 'an', 'and', 'another', 'any', 'anybody', 'anyhow', 'anyone', 'anything', 'anyway', 'anywhere', 'apart', 'are', 'around', 'as', 'at', 'av', 'be', 'became', 'because', 'become', 'becomes', 'becoming', 'been', 'before', 'beforehand', 'behind', 'being', 'below', 'beside', 'besides', 'between', 'beyond', 'both', 'but', 'by', 'can', 'cannot', 'canst', 'certain', 'cf', 'choose', 'contrariwise', 'cos', 'could', 'cu', 'day', 'do', 'does', "doesn't", 'doing', 'dost', 'doth', 'double', 'down', 'dual', 'during', 'each', 'either', 'else', 'elsewhere', 'enough', 'et', 'etc', 'even', 'ever', 'every', 'everybody', 'everyone', 'everything', 'everywhere', 'except', 'excepted', 'excepting', 'exception', 'exclude', 'excluding', 'exclusive', 'far', 'farther', 'farthest', 'few', 'ff', 'first', 'for', 'formerly', 'forth', 'forward', 'from', 'front', 'further', 'furthermore', 'furthest', 'get', 'go', 'had', 'halves', 'hardly', 'has', 'hast', 'hath', 'have', 'he', 'hence', 'henceforth', 'her', 'here', 'hereabouts', 'hereafter', 'hereby', 'herein', 'hereto', 'hereupon', 'hers', 'herself', 'him', 'himself', 'hindmost', 'his', 'hither', 'hitherto', 'how', 'however', 'howsoever', 'i', 'ie', 'if', 'in', 'inasmuch', 'inc', 'include', 'included', 'including', 'indeed', 'indoors', 'inside', 'insomuch', 'instead', 'into', 'inward', 'inwards', 'is', 'it', 'its', 'itself', 'just', 'kind', 'kg', 'km', 'last', 'latter', 'latterly', 'less', 'lest', 'let', 'like', 'little', 'ltd', 'many', 'may', 'maybe', 'me', 'meantime', 'meanwhile', 'might', 'moreover', 'most', 'mostly', 'more', 'mr', 'mrs', 'ms', 'much', 'must', 'my', 'myself', 'namely', 'need', 'neither', 'never', 'nevertheless', 'next', 'no', 'nobody', 'none', 'nonetheless', 'noone', 'nope', 'nor', 'not', 'nothing', 'notwithstanding', 'now', 'nowadays', 'nowhere', 'of', 'off', 'often', 'ok', 'on', 'once', 'one', 'only', 'onto', 'or', 'other', 'others', 'otherwise', 'ought', 'our', 'ours', 'ourselves', 'out', 'outside', 'over', 'own', 'per', 'perhaps', 'plenty', 'provide', 'quite', 'rather', 'really', 'round', 'said', 'sake', 'same', 'sang', 'save', 'saw', 'see', 'seeing', 'seem', 'seemed', 'seeming', 'seems', 'seen', 'seldom', 'selves', 'sent', 'several', 'shalt', 'she', 'should', 'shown', 'sideways', 'since', 'slept', 'slew', 'slung', 'slunk', 'smote', 'so', 'some', 'somebody', 'somehow', 'someone', 'something', 'sometime', 'sometimes', 'somewhat', 'somewhere', 'spake', 'spat', 'spoke', 'spoken', 'sprang', 'sprung', 'stave', 'staves', 'still', 'such', 'supposing', 'than', 'that', 'the', 'thee', 'their', 'them', 'themselves', 'then', 'thence', 'thenceforth', 'there', 'thereabout', 'thereabouts', 'thereafter', 'thereby', 'therefore', 'therein', 'thereof', 'thereon', 'thereto', 'thereupon', 'these', 'they', 'this', 'those', 'thou', 'though', 'thrice', 'through', 'throughout', 'thru', 'thus', 'thy', 'thyself', 'till', 'to', 'together', 'too', 'toward', 'towards', 'ugh', 'unable', 'under', 'underneath', 'unless', 'unlike', 'until', 'up', 'upon', 'upward', 'upwards', 'us', 'use', 'used', 'using', 'very', 'via', 'vs', 'want', 'was', 'we', 'week', 'well', 'were', 'what', 'whatever', 'whatsoever', 'when', 'whence', 'whenever', 'whensoever', 'where', 'whereabouts', 'whereafter', 'whereas', 'whereat', 'whereby', 'wherefore', 'wherefrom', 'wherein', 'whereinto', 'whereof', 'whereon', 'wheresoever', 'whereto', 'whereunto', 'whereupon', 'wherever', 'wherewith', 'whether', 'whew', 'which', 'whichever', 'whichsoever', 'while', 'whilst', 'whither', 'who', 'whoa', 'whoever', 'whole', 'whom', 'whomever', 'whomsoever', 'whose', 'whosoever', 'why', 'will', 'wilt', 'with', 'within', 'without', 'worse', 'worst', 'would', 'wow', 'ye', 'yet', 'year', 'yippee', 'you', 'your', 'yours', 'yourself', 'yourselves']
self.__short_stopwords = ['a', 'an', 'the', 'yes', 'no', 'thanks']
self.__middle_stopwords = ['in', 'on', 'at', 'a', 'an', 'is', 'be', 'was', 'I', 'you', 'the', 'do', 'did', 'of', 'so', 'for', 'with', 'yes', 'thanks']
# The NLTK stopwords cause a problem if they have not been downloaded, so we need a check for that.
try:
self.__nltk_stopwords = nltk.corpus.stopwords.words('english')
except:
self.__nltk_stopwords = []
self.__stopwords = self.__middle_stopwords # Default.
self.cutoffdate = False # Needed for classification splits.
def _unzip_and_load(self, zipped_catfile):
ziplocation = os.path.dirname(zipped_catfile)
cat = os.path.basename(zipped_catfile).split('.')[0]
questionfile = ziplocation + '/' + cat + '/' + cat + '_questions.json'
answerfile = ziplocation + '/' + cat + '/' + cat + '_answers.json'
commentfile = ziplocation + '/' + cat + '/' + cat + '_comments.json'
userfile = ziplocation + '/' + cat + '/' + cat + '_users.json'
if os.path.exists(questionfile) and os.path.exists(answerfile) and os.path.exists(userfile) and os.path.exists(commentfile):
pass # All good, we don't need to unzip anything
else:
zip_ref = zipfile.ZipFile(zipped_catfile, 'r')
zip_ref.extractall(ziplocation)
qf = codecs.open(questionfile, 'r', encoding='utf-8')
self.postdict = json.load(qf)
af = codecs.open(answerfile, 'r', encoding='utf-8')
self.answerdict = json.load(af)
cf = codecs.open(commentfile, 'r', encoding='utf-8')
self.commentdict = json.load(cf)
uf = codecs.open(userfile, 'r', encoding='utf-8')
self.userdict = json.load(uf)
print "Loaded all data from", zipped_catfile
def tokenize(self, s):
''' Takes a string as input, tokenizes it using NLTK (http://www.nltk.org) and returns a list of the tokens. '''
return nltk.word_tokenize(s) # The NLTK tokenizer cuts things like 'cannot' into 'can' and 'not'.
########################
# GENERAL POST METHODS #
########################
def get_posts_with_duplicates(self):
''' Takes no input and returns a list of all posts that have at least one duplicate. '''
dups = []
for p in self.postdict:
if len(self.postdict[p]['dups']) > 0:
dups.append(p)
return dups
def get_all_duplicate_pairs(self):
''' Takes no input an returns a list of duplicate question pairs as tuples of ids. '''
duppairs = []
for p in self.postdict:
for d in self.postdict[p]['dups']:
duppairs.append((p, d))
return duppairs
def get_posts_without_duplicates(self):
''' Takes no input and returns a list of all posts that don't have any duplicates. '''
nodups = []
for p in self.postdict:
if len(self.postdict[p]['dups']) == 0:
nodups.append(p)
return nodups
def get_posts_with_related(self):
''' Takes no input and returns a list of all posts that have related questions. '''
related = []
for p in self.postdict:
if len(self.postdict[p]['related']) > 0:
related.append(p)
return related
def get_all_related_pairs(self):
''' Takes no input an returns a list of related question pairs as tuples of ids. '''
relpairs = []
for p in self.postdict:
for d in self.postdict[p]['related']:
relpairs.append((p, d))
return relpairs
def get_posts_with_and_without_duplicates(self):
''' Takes no input and returns two lists: one with all posts that have at least one duplicate, and one with all posts that don't have any duplicates. In that order.
Calling this method is quicker than calling get_posts_with_duplicates() followed by get_posts_without_duplicates() if you want both dups and non-dups. '''
nodups = []
dups = []
for p in self.postdict:
if len(self.postdict[p]['dups']) == 0:
nodups.append(p)
else:
dups.append(p)
return dups, nodups
def get_posts_dups_nodups_and_related(self):
''' Takes no input and return three lists: one with all posts that have at least one duplicate, one with all posts that have at least one related question, and one with all posts that don't have any duplicates or related questions. In that order.
Calling this method is quicker than calling get_posts_with_duplicates(), followed by get_posts_with_related(), followed by get_posts_without_duplicates() if you want all three types of questions.
There may be overlap in the list of posts with duplicates and posts with related questions, because posts can have bot duplicates and related questions. '''
nodups = []
dups = []
related = []
for p in self.postdict:
if len(self.postdict[p]['dups']) == 0 and len(self.postdict[p]['related']) == 0:
nodups.append(p)
if len(self.postdict[p]['related']) > 0:
related.append(p)
if len(self.postdict[p]['dups']) > 0:
dups.append(p)
return dups, related, nodups
def get_older_posts(self, postid):
''' Takes a post id as input and returns a list of question ids that are older than the input post id. '''
allordered = [i[0] for i in self.get_ordered_list_of_posts()]
postindex = allordered.index(postid)
return allordered[postindex:]
def get_ordered_list_of_posts(self):
''' Takes no input and returns a list of tuples (postid, datetime object), ordered chronologically from newest to oldest post. '''
return sorted([(i, datetime.datetime.strptime(self.get_postdate(i), '%Y-%m-%d')) for i in self.postdict], key=lambda x: x[1], reverse=True)
def get_random_postid(self):
''' Takes no input and returns a random post id. '''
allids = self.postdict.keys()
return random.choice(allids)
def get_random_pair_of_posts(self):
''' Takes no input and returns a tuple with two random post ids and a duplicate verdict. The second is always lower than the first.
Example: (4865, 553, 'dup')
Other values for the verdict are: 'related' and 'nondup'. '''
allids = self.postdict.keys()
id1 = random.choice(allids)
id2 = random.choice(allids)
while id2 >= id1:
id2 = random.choice(allids)
if id2 in self.postdict[id1]['dups']:
return (id1, id2, 'dup')
elif id2 in self.postdict[id1]['related']:
return (id1, id2, 'related')
else:
return (id1, id2, 'nondup')
def get_all_postids(self):
''' Takes no input and returns a list of ALL post ids. '''
return self.postdict.keys()
def get_true_label(self, postid1, postid2):
''' Takes two postids as input and returns the true label, which is one of "dup", "nodup" or "related". '''
if postid1 in self.postdict[postid2]['dups']:
return "dup"
elif postid1 in self.postdict[postid2]['related']:
return "related"
elif postid2 in self.postdict[postid1]['dups']:
return "dup"
elif postid2 in self.postdict[postid1]['related']:
return "related"
else:
return "nodup"
###########################
# PARTICULAR POST METHODS #
###########################
def get_posttitle(self, postid):
''' Takes a post id as input and returns the title of the post. '''
return self.postdict[postid]["title"]
def get_postbody(self, postid):
''' Takes a post id as input and returns the body of the post. '''
return self.postdict[postid]["body"]
def get_post_title_and_body(self, postid):
''' Takes a post id as input and returns the title and the body of the post together as one string, so in other words, the full initial post. '''
t = self.postdict[postid]["title"]
b = self.postdict[postid]["body"]
return t + ' ' + b
def get_postdate(self, postid):
''' Takes a post id as input and returns the date the post was posted in YYYY-MM-DD format. '''
cdate = datetime.datetime.strptime(self.postdict[postid]['creationdate'], "%Y-%m-%dT%H:%M:%S.%f")
return str(cdate.year) + '-' + cdate.strftime('%m') + '-' + cdate.strftime('%d')
def get_posttime(self, postid):
''' Takes a post id as input and returns the time the post was posted in HH:MM:SS format. '''
cdate = datetime.datetime.strptime(self.postdict[postid]['creationdate'], "%Y-%m-%dT%H:%M:%S.%f")
return cdate.strftime('%H') + ':' + cdate.strftime('%M') + ':' + cdate.strftime('%S')
def get_postviewcount(self, postid):
''' Takes a post id as input and returns the number of times the post has been looked at by users. '''
return self.postdict[postid]["viewcount"]
def get_postfavoritecount(self, postid):
''' Takes a post id as input and returns an integer representing the nr of times this post has been favoured by a user.
More information on what that means can be found here: http://meta.stackexchange.com/questions/53585/how-do-favorite-questions-work '''
return self.postdict[postid]['favoritecount']
def get_postscore(self, postid):
''' Takes a post id as input and returns the score of the post. This is the number of upvotes minus the number of downvotes is has received. '''
return self.postdict[postid]['score']
def get_postuserid(self, postid):
''' Takes a post id as input and returns the userid of the person that posted it. Returns False if the user is not known. '''
return self.postdict[postid]['userid']
def get_duplicates(self, postid):
''' Takes a post id as input and returns a list of ids of posts that have been labeled as a duplicate of it. '''
return self.postdict[postid]['dups']#.keys()
def get_related(self, postid):
''' Takes a post id as input and returns a list of ids of posts that have been labeled as related to it. '''
return self.postdict[postid]['related']
def get_posttags(self, postid):
''' Takes a post id as input and returns a list of tags. '''
return self.postdict[postid]['tags']
def get_duptagdates(self, postid1, postid2):
''' Takes two post ids as input and returns a list of dates on which this pair received a duplicate tag, in %Y-%m-%dT%H:%M:%S.%f format.
Usually the list only contains one date, but sometimes it contains multiple. '''
if postid1 in self.postdict[postid2]['dups']:
ddates_raw = self.postdict[postid2]['dups'][postid1]['votedates']
else:
ddates_raw = self.postdict[postid1]['dups'][postid2]['votedates']
ddates = []
for ddate in ddates_raw:
#datet = datetime.datetime.strptime(ddate, "%Y-%m-%dT%H:%M:%S.%f")
#dates.append(str(datet.year) + '-' + datet.strftime('%m') + '-' + datet.strftime('%d'))
ddates.append(ddate)
return ddates
def get_first_duptagdate(self, postid):
''' Takes one postid as input and returns the date on which this post was tagged as a duplicate for the first time, in %Y-%m-%dT%H:%M:%S.%f format,
or 0 if the post has not been tagged as a duplicate (yet). '''
dups = self.get_duplicates(postid)
dupdates = []
for dup in dups:
checkdates = self.postdict[postid]['dups'][dup]['votedates']
for c in checkdates:
cdate = datetime.datetime.strptime(c, "%Y-%m-%dT%H:%M:%S.%f")
dupdates.append(c)
dupdates.sort()
#print dupdates
if len(dupdates) > 0:
return dupdates[0]
else:
0
def get_dupvoters(self, postid1, postid2):
''' Takes two post ids as input and returns a list of the users that have voted for these two questions to be duplicates. '''
if postid1 in self.postdict[postid2]['dups']:
return self.postdict[postid2]['dups'][postid1]['voters']
else:
return self.postdict[postid1]['dups'][postid2]['voters']
##################
# ANSWER METHODS #
##################
def get_answers(self, postid):
''' Takes a post id as input and returns a list of answer ids. '''
return self.postdict[postid]["answers"]
def get_answercount(self, postid):
''' Takes a post id as input and returns an integer representing the number of answers it has received. '''
return len(self.postdict[postid]['answers'])
def get_answer_parentid(self, answerid):
''' Takes an answer id as input and returns its parent id: the id of the post it is an answer of. '''
return self.answerdict[answerid]['parentid']
def get_acceptedanswer(self, postid):
''' Takes a post id as input and returns the answer id of the accepted answer if it exists, else it returns False. '''
if postid not in self.postdict:
raise KeyError(postid + " is not a valid post id for this subforum.")
if 'acceptedanswer' in self.postdict[postid]:
return self.postdict[postid]['acceptedanswer']
else:
return False
def get_acceptedanswer_date(self, answerid):
''' Takes an answer id as input and returns the date at which it was selected as the best answer in YYYY-MM-DD format, if it exists. Else it returns 0. '''
if self.answerdict[answerid]['acceptedanswerdate'] == 0:
return 0
else:
adate = datetime.datetime.strptime(self.answerdict[answerid]['acceptedanswerdate'], "%Y-%m-%dT%H:%M:%S.%f")
return str(adate.year) + '-' + adate.strftime('%m') + '-' + adate.strftime('%d')
def get_answerbody(self, answerid):
''' Takes an answer id as input and returns the body of the answer. That is the text of the answer. '''
return self.answerdict[answerid]['body']
def get_answerdate(self, answerid):
''' Takes an answer id as input and returns the date the answer was posted in YYYY-MM-DD format. '''
cdate = datetime.datetime.strptime(self.answerdict[answerid]['creationdate'], "%Y-%m-%dT%H:%M:%S.%f")
return str(cdate.year) + '-' + cdate.strftime('%m') + '-' + cdate.strftime('%d')
def get_answertime(self, answerid):
''' Takes an answer id as input and returns the time the answer was posted in HH:MM:SS format. '''
cdate = datetime.datetime.strptime(self.answerdict[answerid]['creationdate'], "%Y-%m-%dT%H:%M:%S.%f")
return cdate.strftime('%H') + ':' + cdate.strftime('%M') + ':' + cdate.strftime('%S')
def get_answerscore(self, answerid):
''' Takes an answer id as input and returns an integer representing the score of the answer. This is the number of upvotes minus the number of downvotes is has received. '''
return self.answerdict[answerid]["score"]
def get_answeruserid(self, answerid):
''' Takes an answer id as input and returns the userid of the person that posted it. Returns False if the user is not known. '''
return self.answerdict[answerid]['userid']
###################
# COMMENT METHODS #
###################
def get_post_comments(self, postid):
''' Takes a post id as input and returns a list of comment ids. '''
return self.postdict[postid]['comments']
def get_answer_comments(self, answerid):
''' Takes an answer id as in put and returns a list of comment ids. '''
return self.answerdict[answerid]['comments']
def get_post_commentcount(self, postid):
''' Takes a post id as input and returns and integer representing the number of comments this post has received. '''
return len(self.postdict[postid]['comments'])
def get_answer_commentcount(self, answerid):
''' Takes an answer id as input and returns and integer representing the number of comments this answer has received. '''
return len(self.answerdict[answerid]['comments'])
def get_comment_parentid(self, commentid):
''' Takes a comment id as input and returns its parent id: the id of the post or answer it is a comment to. '''
return self.commentdict[commentid]['parentid']
def get_comment_parenttype(self, commentid):
''' Takes a comment id as input and returns either 'question' or 'answer', depending on the type of its parent id. '''
return self.commentdict[commentid]['parenttype']
def get_commentbody(self, commentid):
''' Takes a comment id as input and returns the body of the comment. '''
return self.commentdict[commentid]['body']
def get_commentdate(self, commentid):
''' Takes a comment id as input and returns the date the comment was posted, in YYYY-MM-DD format. '''
cdate = datetime.datetime.strptime(self.commentdict[commentid]['creationdate'], "%Y-%m-%dT%H:%M:%S.%f")
return str(cdate.year) + '-' + cdate.strftime('%m') + '-' + cdate.strftime('%d')
def get_commenttime(self, commentid):
''' Takes a comment id as input and returns the time the comment was posted, in HH:MM:SS format. '''
cdate = datetime.datetime.strptime(self.commentdict[commentid]['creationdate'], "%Y-%m-%dT%H:%M:%S.%f")
return cdate.strftime('%H') + ':' + cdate.strftime('%M') + ':' + cdate.strftime('%S')
def get_commentscore(self, commentid):
''' Takes a comment id as input and returns an integer representing the score of the comment. This is the number of upvotes minus the number of downvotes is has received. '''
return self.commentdict[commentid]['score']
def get_commentuserid(self, commentid):
''' Takes a comment id as input and returns the id of the user that posted the comment. '''
return self.commentdict[commentid]['userid']
################
# USER METHODS #
################
def get_all_users(self):
''' Takes no input and returns a list of all users. '''
return self.userdict.keys()
def get_user_reputation(self, userid):
''' Takes a user id as input and outputs an integer representing the reputation of the user.
Information on what this means and how it is calculated can be found here http://stackoverflow.com/help/whats-reputation '''
return self.userdict[userid]['rep']
def get_user_views(self, userid):
''' Takes a user id as input and outputs an integer representing how often people have viewed a post by this user. '''
return self.userdict[userid]['views']
def get_user_upvotes(self, userid):
''' Takes a user id as input and outputs an integer representing how many upvotes on posts or answers this user has received. '''
return self.userdict[userid]['upvotes']
def get_user_downvotes(self, userid):
''' Takes a user id as input and outputs an integer representing how many downvotes on posts or answers this user has received. '''
return self.userdict[userid]['downvotes']
def get_user_joindate(self, userid):
''' Takes a user id as input and outputs the date this user joined this subforum, in YYYY-MM-DD format. '''
cdate = datetime.datetime.strptime(self.userdict[userid]['date_joined'], "%Y-%m-%dT%H:%M:%S.%f")
return str(cdate.year) + '-' + cdate.strftime('%m') + '-' + cdate.strftime('%d')
def get_user_lastaccess(self, userid):
''' Takes a user id as input and outputs the last time this user has logged into this subforum, in YYYY-MM-DD format. '''
cdate = datetime.datetime.strptime(self.userdict[userid]['lastaccessdate'], "%Y-%m-%dT%H:%M:%S.%f")
return str(cdate.year) + '-' + cdate.strftime('%m') + '-' + cdate.strftime('%d')
def get_user_age(self, userid):
''' Takes a user id as input and outputs the user's age as an integer, if known. Else it returns 'unknown'. '''
if 'age' in self.userdict[userid]:
return self.userdict[userid]['age']
else:
return 'unknown'
def get_user_posts(self, userid):
''' Takes a user id as input and returns a list of the question posts he/she has made. '''
return self.userdict[userid]['questions']
def get_user_answers(self, userid):
''' Takes a user id as input and returns a list of the answers he/she has written. '''
return self.userdict[userid]['answers']
def get_user_badges(self, userid):
''' Takes a user id as input and returns a list of the badges this user has earned.
Information on what badges are and which ones can be earned can be found here: http://stackoverflow.com/help/badges '''
return self.userdict[userid]['badges']
####################
# Cleaning methods #
####################
@property
def stopwords(self):
''' Returns the current list of words that is used as the stop word list. It can be accessed via self.stopwords'''
return self.__stopwords
def supply_stopwords(self, filename):
''' Takes as input a plain text file encoded in UTF-8 with one stop word per line and saves these internally in a stop word list.
This list will be used in cleaning if perform_cleaning() is called with remove_stopwords=True. '''
self.__stopwords = []
inputf_open = codecs.open(filename, 'r', encoding='utf-8')
inputf = inputf_open.readlines()
inputf_open.close()
for line in inputf:
line = line.rstrip()
self.__stopwords.append(line)
def change_to_default_stopwords(self, stopwordset='middle'):
''' Changes the stopword list to one of the supplied ones: 'nltk', 'indri', 'short' or 'middle'. 'Middle' is the default.
The NLTK stopword list contains 127 stopwords. (http://www.nltk.org/book/ch02.html#code-unusual)
The Indri stopword list contains 418 stopwords. (http://www.lemurproject.org/stopwords/stoplist.dft)
Short = ["a", "an", "the", "yes", "no", "thanks"]
Middle = ["in", "on", "at", "a", "an", "is", "be", "was", "I", "you", "the", "do", "did", "of", "so", "for", "with", "yes", "thanks"]
To be able to use the NLTK stopwords, they need to be downloaded first. See: http://www.nltk.org/data.html for more info.
If the data is not downloaded first, the script will default to the NLTK stopword list of November 2015.
'''
if stopwordset == 'nltk':
if self.__nltk_stopwords != []:
self.__stopwords = self.__nltk_stopwords
else: # This can happen if the NLTK stopwords have not been downloaded yet. Defaulting to the NLTK stopword list of November 2015.
self.__stopwords = [u'i', u'me', u'my', u'myself', u'we', u'our', u'ours', u'ourselves', u'you', u'your', u'yours', u'yourself', u'yourselves', u'he', u'him', u'his', u'himself', u'she', u'her', u'hers', u'herself', u'it', u'its', u'itself', u'they', u'them', u'their', u'theirs', u'themselves', u'what', u'which', u'who', u'whom', u'this', u'that', u'these', u'those', u'am', u'is', u'are', u'was', u'were', u'be', u'been', u'being', u'have', u'has', u'had', u'having', u'do', u'does', u'did', u'doing', u'a', u'an', u'the', u'and', u'but', u'if', u'or', u'because', u'as', u'until', u'while', u'of', u'at', u'by', u'for', u'with', u'about', u'against', u'between', u'into', u'through', u'during', u'before', u'after', u'above', u'below', u'to', u'from', u'up', u'down', u'in', u'out', u'on', u'off', u'over', u'under', u'again', u'further', u'then', u'once', u'here', u'there', u'when', u'where', u'why', u'how', u'all', u'any', u'both', u'each', u'few', u'more', u'most', u'other', u'some', u'such', u'no', u'nor', u'not', u'only', u'own', u'same', u'so', u'than', u'too', u'very', u's', u't', u'can', u'will', u'just', u'don', u'should', u'now']
elif stopwordset == 'indri':
self.__stopwords = self.__indri_stopwords
elif stopwordset == 'short':
self.__stopwords = self.__short_stopwords
else:
self.__stopwords = self.__middle_stopwords # DEFAULT
def perform_cleaning(self, s, maxcodelength=150, remove_stopwords=False, remove_punct=False, stem=False):
''' Takes a string as input and returns a cleaned version.
- The string will be lowercased and newlines removed.
- HTML tags will be removed.
- Mentions of possible duplicates will be removed.
- URLs pointing to other StackExchange threads are turned into 'stackexchange-url'.
- Blocks of code will be removed.
- Contracted forms will be expanded. E.g. "didn't" --> "did not".
- '&' will be turned into 'and'.
- Other HTML entities will be removed, and string matching the following pattern too: '?[a-z]+;'.
- Whitespace is added around punctuation
OPTIONAL ARGUMENTS:
maxcodelength: the maximum length of code blocks that will not be removed. Default: 150.
remove_stopwords: removed stop words. (Values: True or False)
remove_punct: punctuation is removed, except for punctuation in URLs and numbers. (Values: True or False)
stem: stemming is performed via the Porter stemmer as implemented in the NLTK (http://www.nltk.org/). (Values: True or False)
'''
s, codes = self._deal_with_code(s,maxcodelength)
s = s.lower()
s = re.sub('\n', ' ', s)
s = self._remove_tags(s)
s = self._expand_contractions(s)
s = self._general_cleaning(s,codes,remove_punct)
if remove_stopwords:
s = self._remove_stopwords(s)
if stem:
s = self._stem(s)
s = self._fix_exceptions(s)
# TODO: consider removing dashes between hyphenated words (far-off -> faroff), and removing full stops in acronyms/initials (U.N. -> UN). It helps for METEOR apparently (http://www.cs.cmu.edu/~alavie/METEOR/pdf/meteor-wmt11.pdf). U.S.-based will become US based.
return s
def _fix_exceptions(self, s):
''' Takes a string as input, applies a bunch of regexes to it to fix exceptions that have accidentally been changed, and returns the new string. '''
s = re.sub(' \. net ', ' .net', s)
s = re.sub(' i \. e ', ' i.e. ', s)
# fix extensions
s = re.sub(' \. jpeg ', '.jpeg ', s)
s = re.sub(' \. jpg ', '.jpg ', s)
return s
def _deal_with_code(self, s, maxcodelength):
''' Takes a string as input, finds all code blocks in it and replace them with HHHH to protect them from whitespace addition, lower casing etc. Then returns the new string and a list of the code blocks so we can replace them after more cleaning. '''
codepat = re.compile(r'[^<]+')
codes = re.findall(codepat, s) # re.M for multiline matching not necessary?
n = 0
newcodes = []
for c in codes:
if len(c) < maxcodelength + 13: # two code tags are 13 characters
s = re.sub(re.escape(c), 'HHHH' + str(n), s)
# Remove brackets if other half is missing. Else we'll have problems when we try to put them back.
if re.search(r'\)', c) and not re.search(r'\(', c):
c = re.sub(r'\)', '', c)
if re.search(r'\(', c) and not re.search(r'\)', c):
c = re.sub(r'\(', '', c)
c = re.sub(r'\n', ' ', c, re.M) # remove real newlines
c = re.sub(r'\\n', r'\\\\n', c) # keep and escape \n in things like latex's \newcommand{}.
c = re.sub(r'\s+', ' ', c)
c = re.sub(r'', '', c)
c = re.sub(r'', '', c)
newcodes.append(c)
n += 1
else:
s = re.sub(re.escape(c), '', s) # Remove large code blocks
return s, newcodes
def very_basic_cleaning(self, s):
s = self.url_cleaning(s)
s = self.strip_tags(s)
s = ' '.join(s.split()) # remove multiple whitespaces
s = re.sub('\n+', ' ', s)
return s
def url_cleaning(self, s):
''' Takes a string as input and removes references to possible duplicate posts, and other stackexchange urls. '''
posduppat = re.compile(r'
(.|\n)+?Possible Duplicate(.|\n)+?', re.MULTILINE) s = re.sub(posduppat, '', s) s = re.sub(r']+stackexchange[^>]+>([^<]+)', r'stackexchange-url ("\1")', s) s = re.sub(r']+stackoverflow[^>]+>([^<]+)', r'stackexchange-url ("\1")', s) return s def strip_tags(self, html): # Source: http://stackoverflow.com/questions/753052/strip-html-from-strings-in-python s = MLStripper() s.feed(html) return s.get_data() def _remove_stopwords(self, s): ''' Takes a string as input, removes the stop words in the current stop word list, and returns the result. The current stop word list can be accessed via self.stopwords, or altered by calling supply_stopwords(). ''' words = nltk.word_tokenize(s) # The NLTK tokenizer cuts things like 'cannot' into 'can' and 'not'. words_split = s.split() if 'cannot' in words_split: # which we'd like to keep. location = words_split.index('cannot') words_split[location] = 'can' words_split.insert(location + 1, 'not') counter = 0 filteredwords = [] prevw_in_split = True for w in words: # It used to be so beautifully simple, until I found out NLTK sometimes splits things wrongly. #if w in self.__stopwords: # pass # skip it, we don't want it. #else: # filteredwords.append(w) if words_split[counter] == w: # word was correctly split if w not in self.__stopwords: filteredwords.append(w) counter += 1 prevw_in_split = True elif prevw_in_split: # previous word was fine, but this is the first part of a wrongly split word. filteredwords.append(w) prevw_in_split = False else: # this is a subsequent part of a wrongly split word newword = filteredwords[-1] + w filteredwords[-1] = newword if words_split[counter] == newword: counter += 1 prevw_in_split = True else: prevw_in_split = False cleanstring = ' '.join(filteredwords) cleanstring = self._fix_abbreviations(cleanstring) return cleanstring def _stem(self, s): ''' Takes a string as input and applies the Porter stemmer as implemented in the NLTK (http://www.nltk.org/). Returns the result. ''' words = nltk.word_tokenize(s) words_split = s.split() if 'cannot' in words_split: location = words_split.index('cannot') words_split[location] = 'can' words_split.insert(location + 1, 'not') counter = 0 newwords = [] prevw_in_split = True for w in words: # It used to be so beautiful and simple, until I found out that NLTK splits some things wrongly... #neww = nltk.PorterStemmer().stem_word(w) #newwords.append(neww) if words_split[counter] == w: # word was correctly split neww = nltk.PorterStemmer().stem_word(w) newwords.append(neww) counter += 1 prevw_in_split = True elif prevw_in_split: # previous word was fine, but this is the first part of a wrongly split word. newwords.append(w) prevw_in_split = False else: # this is a subsequent part of a wrongly split word newword = newwords[-1] + w if words_split[counter] == newword: newwords[-1] = nltk.PorterStemmer().stem_word(newword) counter += 1 prevw_in_split = True else: newwords[-1] = newword prevw_in_split = False news = ' '.join(newwords) news = self._fix_abbreviations(news) return news def _fix_abbreviations(self, s): ''' Takes as input a string tokenized by nltk and joined again, and outputs a version in which the abbreviations have been fixed. That means the final dot has been glued to the abbreviation once more.''' if re.search(r' ([a-z]\.[a-z])+ \.', s): found = re.search(r'( ([a-z]\.[a-z])+ \.)', s) abbr = found.group(1) newabbr = re.sub(' ', '', abbr) s = re.sub(abbr, ' ' + newabbr, s) return s def _remove_tags(self, s): ''' Takes a string as input and removes HTML tags, except for code tags, which are remove in general_cleaning. Also removes mentions of possible duplicates and changes URLs that point to other StackExchange threads into 'stackexahcnge-url'. ''' s = re.sub(r"
I\'m implementing a mobile-friendly version of our corporate web site and will be using WURFL to detect mobile browsers and redirect them to our mobile site. Having recently purchased an Android tablet, I\'ve found that many sites consider it to be a mobile device even though it has a large 10" screen and it\'s perfectly capable of handling sites designed using standard desktop resolutions.
\n\nMy plan is to use WURFL, examine the device capabilities and treat anything with a resolution width of less than 700px as a mobile device, but I\'d like some input as to that sweet spot for determining mobile vs desktop.
\n' >>> o.perform_cleaning(o.get_postbody('18957')) u'i am implementing a mobile-friendly version of our corporate web site and will be using wurfl to detect mobile browsers and redirect them to our mobile site . having recently purchased an android tablet , i have found that many sites consider it to be a mobile device even though it has a large 10" screen and it is perfectly capable of handling sites designed using standard desktop resolutions . my plan is to use wurfl , examine the device capabilities and treat anything with a resolution width of less than 700px as a mobile device , but i would like some input as to that sweet spot for determining mobile vs desktop .' >>> for a in o.get_answers('18957'): ... print a, o.get_answerscore(a) ... 18985 1 18980 0 >>> o.get_posttags(o.get_random_postid()) [u'wordpress', u'redirects', u'blog', u'plugin'] >>> o.get_postuserid('18957') u'1907' >>> o.get_user_posts('1907') [u'18957'] >>> o.get_user_views('1907') 6 >>> o.stopwords ['in', 'on', 'at', 'a', 'an', 'is', 'be', 'was', 'I', 'you', 'the', 'do', 'did', 'of', 'so', 'for', 'with'] >>> o.supply_stopwords('new_stopwords_testfile.txt') >>> o.stopwords [u'new_stopword1', u'new_stopword2', u'new_stopword3'] >>> o.change_to_default_stopwords() >>> o.stopwords ['in', 'on', 'at', 'a', 'an', 'is', 'be', 'was', 'I', 'you', 'the', 'do', 'did', 'of', 'so', 'for', 'with']''' usage_text += '\n\n -----------------------------' usage_text += '\n\n Please see the README file that came with this script for more information on the data.\n' print usage_text sys.exit(' ') #------------------------------- if __name__ == "__main__": if len(sys.argv[1:]) != 1: usage() else: main(sys.argv[1])