python - What is this dictionary assignment doing? -
i learning python , trying use perform sentiment analysis. following online tutorial link: http://www.alex-hanna.com/tworkshops/lesson-6-basic-sentiment-analysis/. have taken piece of code mapper class, excerpt of looks this:
sentimentdict = { 'positive': {}, 'negative': {} } def loadsentiment(): open('sentiment/positive_words.txt', 'r') f: line in f: sentimentdict['positive'][line.strip()] = 1 open('sentiment/negative_words.txt', 'r') f: line in f: sentimentdict['negative'][line.strip()] = 1
here, can see new dictionary created 2 keys, positive , negative, no values.
following this, 2 text files opened , each line stripped , mapped dictionary.
however, = 1 part for? why required (and if isn't how removed?)
the loop creates nested dictionary, , sets values 1, presumably use keys way weed out duplicate values.
you use sets instead , avoid = 1
value:
sentimentdict = {} def loadsentiment(): open('sentiment/positive_words.txt', 'r') f: sentimentdict['positive'] = {line.strip() line in f} open('sentiment/negative_words.txt', 'r') f: sentimentdict['negative'] = {line.strip() line in f}
note don't need create initial dictionaries; can create whole set 1 statement, set comprehension.
if other code does rely on dictionaries values being set 1
(perhaps update counts @ later stage), it'd more performant use dict.fromkeys()
class method instead:
sentimentdict = {} def loadsentiment(): open('sentiment/positive_words.txt', 'r') f: sentimentdict['positive'] = dict.fromkeys((line.strip() line in f), 1) open('sentiment/negative_words.txt', 'r') f: sentimentdict['negative'] = dict.fromkeys((line.strip() line in f), 1)
looking @ source blog article shows dictionaries used membership testing against keys, using sets here better , transparent rest of code boot.
Comments
Post a Comment