您可以将words
转换为set
,使查找会更快。这应该会提高程序的性能,因为查找列表中的值必须一次遍历列表中的一个元素(O(n)运行时复杂度),但是当您将列表转换为集合时,运行时复杂度将降低到O(1)(恒定时间)。因为集合使用散列来查找元素。
words = {'the', 'or', 'and', 'can', 'help', 'it', 'one', 'two'}
然后每当有比赛,你可以使用sum
函数来计算它像这样
布尔值及其整数等效
在Python,布尔表达式的结果将等于的0
或1
分别为和True
。
>>> True == 1
True
>>> False == 0
True
>>> int(True)
1
>>> int(False)
0
>>> sum([True, True, True])
3
>>> sum([True, False, True])
2
所以每当你是否part in words
,则结果可能是0
或1
,我们sum
所有这些值。
上方所看到的代码是功能上等同于
result = 0
with open('text.txt') as file:
for line in file:
for part in line.split():
if part in words:
result += 1
注:如果你真的想在每当有一个匹配列表以获得1
的,那么你可以简单地将生成器表达式转换为sum
以获得列表理解,如下所示:
with open('text.txt') as file:
print([int(part in words) for line in file for part in line.split()])
字
频率
如果你真的想找到的个别单词的频率在words
,那么你可以使用collections.Counter
这样
from collections import Counter
with open('text.txt') as file:
c = Counter(part for line in file for part in line.split() if part in words)
这将内部统计数文件中出现words
中的每个单词的时间。
按the comment,可以有你的字典,您可以存储正话正分数,并以负分否定词,并指望他们这样
words = {'happy': 1, 'good': 1, 'great': 1, 'no': -1, 'hate': -1}
with open('text.txt') as file:
print(sum(words.get(part, 0) for line in file for part in line.split()))
在这里,我们使用words.get
词典为了获得存储在单词中的值,并且如果在词典中找不到该单词(既不是好词也不是坏词),则返回默认值0
。
你想找到比赛的数量吗? – thefourtheye