【问题标题】:How to count words in a file using python >2.0 [duplicate]如何使用python> 2.0计算文件中的单词[重复]
【发布时间】:2018-04-28 05:42:07
【问题描述】:

我想编写一个可以计算文件中关键字的程序。 示例:我创建了一个列表,其中包含以下关键字。然后我打开一个包含一堆单词的文件,我想计算文件中有多少个关键字。但是无论我做什么,计数总是给我0。我做错了什么?

这是我的代码:

Happy = ['amazed', 'amazing', 'best', 'excellent', 'excited', 'excite', 
         'excites', 'exciting', 'glad', 'greatest', 'happy', 'love',
         'loves', 'loved', 'loving', 'lovin', 'prettiest']

def CountFile():
  file = open("File.txt", "r")
  Count = 0
  for i in file:
    i = i.split()
    if i in Happy:
      count = count + 1
  print("there are" count "keywords")
  return

CountFile()

【问题讨论】:

  • @Julien 我刚开始学习python,我真的看不懂那个代码。
  • 我为什么要关心?阅读教程...
  • @Julien 接受的链接答案仅适用于 python 2。如果有人想在 python 3 中执行此操作或更简单的方法怎么办?
  • @yacc 我做了,但是就像我说的我刚开始学习python,我真的看不懂一些代码
  • @sachindubey 这个问题已经被问和回答了一百万次。一点点研究工作将为您提供 10 种不同的解决方案供您选择。

标签: python computer-science


【解决方案1】:

试试这个代码

Happy = ['amazed', 'amazing', 'best', 'excellent', 'excited', 'excite', 'excites', 'exciting', 'glad', 'greatest', 'happy', 'love', 'loves', 'loved', 'loving', 'lovin', 'prettiest']

def CountFile():
   file = open("File.txt", "r")
   count = 0
   for i in file:
      i = i.split()
      for so in i:
         if so in Happy:  
            count = count + 1
   print("there are %s keywords" %count)

CountFile()

【讨论】:

    【解决方案2】:

    当你做i = i.split()

    i 变成一个列表。您的 i 变量是此处文本文件中的一行。

    你应该可以,

       ...
       words = i.split()
       for w in words:     
         if w in Happy:
           count += 1
       ...
    

    【讨论】:

      猜你喜欢
      • 2011-04-25
      • 2016-01-23
      • 2013-05-05
      • 2014-08-11
      • 2017-10-09
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      • 2014-11-04
      相关资源
      最近更新 更多