This should do what you're looking for, it uses set
& intersection to avoid some of the looping. The steps are —
- get the negative words in the line
- check the location of each word
- if the word after that location is 'laptop' record it
Note that this will only identify the first occurrence of a negative word in a line, so "terrible terrible laptop" will not be a match.
from collections import defaultdict
def run(path):
negWords=defaultdict(int) # A defaultdict(int) will start at 0, can just add.
#load the negative lexicon
negLex=loadLexicon('negative-words.txt')
# ?? Is the above a list or a set, if it's a list convert to set
negLex = set(negLex)
fin=open(path)
for line in fin: #for every line in the file (1 review per line)
line=line.lower().strip().split(' ')
# Can just pass a list to set to make a set of it's items.
review_set = set(line)
# Compare the review set against the neglex set. We want words that are in
# *both* sets, so we can use intersection.
neg_words_used = review_set & negLex
# Is the bad word followed by the word laptop?
for word in neg_words_used:
# Find the word in the line list
ix = line.index(word)
if ix > len(line) - 2:
# Can't have laptop after it, it's the last word.
continue
# The word after this index in the line is laptop.
if line[ix+1] == 'laptop':
negWords[word] += 1
fin.close()
return negWords
If you're only interested in words preceding the word 'laptop', a far more sensible approach would be to look for the word 'laptop', then check the word prior to that to see if it is a negative word. The following example does that.
- find laptop in the current line
- if laptop isn't in the line, or is the first word, skip the line
- get the word before laptop, check against the negative words
- if you have a match add it to our result
This avoids doing lookups for words which are not related to laptops.
from collections import defaultdict
def run(path):
negWords=defaultdict(int) # A defaultdict(int) will start at 0, can just add.
#load the negative lexicon
negLex=loadLexicon('negative-words.txt')
# ?? Is the above a list or a set, if it's a list convert to set
negLex = set(negLex)
fin=open(path)
for line in fin: #for every line in the file (1 review per line)
line=line.lower().strip().split(' ')
try:
ix = line.index('laptop')
except ValueError:
# If we dont' find laptop, continue to next line.
continue
if ix == 0:
# Laptop is the first word of the line, can't check prior word.
continue
previous_word = line[ix-1]
if previous_word in negLex:
# Negative word before the current one.
negWords[previous_word] += 1
fin.close()
return negWords