【发布时间】:2021-06-11 22:18:37
【问题描述】:
所以我正在尝试编写代码来比较两个列表(firstfile.txt 中的 firstfile;secondfile.txt 中的 secondfile)并打印 firstfile 中重叠单词出现在 secondfile 中的次数。
所以,例如,如果在 firstfile(.txt) 我有:
'beautiful', 'day', 'neighborhood', 'sun'
在 secondfile(.txt) 我有
"It's a beautiful day in the neighborhood today. The sun is shining brightly, and the birds are singing.
And now I run into this beautiful lady, whose skin gleams in the sun light."
所以我期望的结果是这样的:
beautiful: 2
day: 1
neighborhood: 1
sun: 2
到目前为止,我想出了以下几点:
results = {}
for i in firstfile:
results[i] = secondfile.count(i)
print(results)
但它会打印出类似的东西
{'beautiful': 0, 'day': 0, 'neighborhood': 0, 'sun': 0}
这显然是不正确的。
我做错了什么?我已经尝试了十几种不同的方法,但对于重叠的单词,它们似乎都没有返回 0 以外的任何东西。代码有问题,还是我应该以特定方式从 firstfile.txt 和 secondfile.txt 创建列表?谢谢大家! (另外,我是 Python 的新手(和一般的编程),所以如果这是一个愚蠢的问题或者我没有把事情说清楚,请原谅我!!)
【问题讨论】:
-
在您的帖子中,
secondfile不是一个列表,而是一个字符串,这也是您的代码只产生 0 个匹配项的原因。 -
如果我将 secondfile 转换为列表会怎样?它看起来像 ['It's', 'a', 'beautiful', 'day', 'in', 'the', 'neighborhood', 'today'] 等。它仍然返回 0 个匹配项
标签: python count nlp frequency