我在计算一个列表中的否定词出现在一个特定词之前的次数。例如,“ThisTerrableLaptop”。指定的单词是“laptop”,我希望在Python中输出“可怕的1”。在
def run(path):
negWords={} #dictionary to return the count
#load the negative lexicon
negLex=loadLexicon('negative-words.txt')
fin=open(path)
for line in fin: #for every line in the file (1 review per line)
line=line.lower().strip().split(' ')
review_set=set() #Adding all the words in the review to a set
for word in line: #Check if the word is present in the line
review_set.add(word) #As it is a set, only adds one time
for word in review_set:
if word in negLex:
if word in negWords:
negWords[word]=negWords[word]+1
else:
negWords[word] = 1
fin.close()
return negWords
if __name__ == "__main__":
print(run('textfile'))
这应该符合您的要求,它使用
set
&intersection来避免一些循环。步骤是-注意,这只会识别一行中第一个出现的否定词,所以“可怕的笔记本电脑”将不匹配。在
如果你只对单词“laptop”前面的单词感兴趣,一个更明智的方法是查找单词“laptop”,然后检查前面的单词,看看它是否是一个否定词。下面的例子就是这样做的。在
这样可以避免查找与笔记本电脑无关的单词。在
^{pr2}$看起来你想对照连续单词检查函数,这里有一种方法,
condition
将针对每个连续单词进行检查。在输出:
^{pr2}$奖金:
只需使用检查3个单词的条件将},就可以搜索3个连续的单词。
zip(w, w[1:])
更改为{您可以通过执行以下操作获得计数器词典:
相关问题 更多 >
编程相关推荐