您可以將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