【问题标题】:Count words from many .txt files计算许多 .txt 文件中的单词
【发布时间】:2018-03-21 15:25:06
【问题描述】:

我想显示每个.txt 文件中出现的每个单词以及它出现的次数。这是我的代码:

listtxt = ['a.txt','b.txt','c.txt',...]
output = open('dictionary.txt','w')
d = {}

for i in listtxt:
   with open(i,'r') as file:
     data = file.read()

     for char in '-.,;”“':
         data=data.replace(char,' ')

     data = data.lower()
     word_list = data.split()

     for word in word_list:
         d[word] = d.get(word,0) +1

     for words, count in d.items():
         output.write(('{} : {} \n'.format(words, count)))

output.close()

当我运行它时,单词和出现次数似乎是分开出现的,这意味着它没有检查上一个文件中的单词。我不知道为什么它不起作用。

【问题讨论】:

  • 我不认为data = data.lower() 以及它之后的所有内容都必须在for char in '-.,;”“' 循环中。
  • 您可能想要使用string.punctuation(先导入string 库之后)而不是'-.,;”“' EG:for char in string.punctuation:
  • @DyZ 我发布这个问题时有一些标签错误,我刚刚编辑了它
  • @Jono2906 成功了,ty。但这并不能解决问题
  • 只是给你一个建议。

标签: python word-count


【解决方案1】:

简单的缩进错误。最后一个循环(for words, count in d.items())需要在第一个循环之外(for i in listtxt)。

标签在 python 中很重要。

【讨论】:

    猜你喜欢
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    相关资源
    最近更新 更多