我有一個函式可以生成句子中單詞的頻率。我也有一個句子串列。
sentences = ["this word is used for testing", "code runs this word", "testing the code now"]
def findFreq():
# create new dict
# word freq finding code
# print dict
for sen in sentences:
findFreq(sen)
這給了我這樣的結果:
{'this': 1, 'word': 1, 'is': 1, 'used': 1, 'for': 1, 'testing': 1}
{'code': 1, 'runs': 1, 'this': 1, 'word': 1}
{'testing': 1, 'the': 1, 'code': 1, 'now': 1}
但我想要這樣的結果:
{'this': 2, 'word': 2, 'is': 1, 'used': 1, 'for': 1, 'testing': 2, 'code': 2, 'runs': 1, 'the': 1, 'now': 1}
我已經看到了將計數器和字典理解與 Set 結合使用的解決方案,但是如何在像上面給出的回圈中運行時將它們組合在一起?
uj5u.com熱心網友回復:
如果您想保留現有代碼,請findFreq
回傳一個 dict(而不是列印它)。Counter
然后在回圈的每次迭代中更新 a for
。
from collections import Counter
c = Counter()
for sen in sentences:
c.update(findFreq(sen))
print(c)
如果您想要更短的解決方案,只需使用
>>> Counter(' '.join(sentences).split())
Counter({'this': 2,
'word': 2,
'is': 1,
'used': 1,
'for': 1,
'testing': 2,
'code': 2,
'runs': 1,
'the': 1,
'now': 1})
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/436886.html