【问题标题】:Count occurrences of overlapping words between txt files计算 txt 文件之间重叠单词的出现次数
【发布时间】: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


【解决方案1】:

您需要将 firstfile 声明为列表:

firstfile = ['beautiful', 'day', 'neighborhood', 'sun']

secondfile = "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."

results = {}

for i in firstfile:
    results[i] = secondfile.count(i)

这对我有用。

【讨论】:

  • 谢谢!如果我的文件有数千个字长并且我无法将它们放入代码中那样的紧凑列表中怎么办? (希望这是有道理的!)
  • 使用上下文管理器和 readlines() 读取它们。像这样:使用 open(path) 作为 f: firstfile = f.readlines()。这将返回一个带有换行符的列表。使用 f.read() 将整个文本作为字符串读取。
  • 好的,现在我的文件看起来像这样: firstfile: 'beautiful', 'day', 'neighborhood', 'sun', etc. secondfile: 'It's', 'a', ' beautiful', 'day', 'in', 'the', 'neighborhood' 等(所有单词都换行)但是现在 print(results) 只返回这个:{} jesus christ
  • 使用 firstfile.split(",") 得到一个列表然后 text = "".join(secondfile).replace(",", "") 得到一个字符串。
猜你喜欢
  • 1970-01-01
  • 2023-04-04
  • 2015-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-24
相关资源
最近更新 更多