如何使用 python >2.0 计算文件中的字数

How to count words in a file using python >2.0

我想写一个程序来计算文件中的关键字。 示例:我创建了一个列表,其中包含以下关键字。然后我打开一个包含一堆单词的文件,我想计算文件中有多少个关键字。但是无论我做什么,计数总是给我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()

当你做 i = i.split()

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

你或许可以,

   ...
   words = i.split()
   for w in words:     
     if w in Happy:
       count += 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()