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

2024-09-27 21:23:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 文件in程序密码示例列表count关键字
2条回答

尝试此代码

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()

当你做i = i.split()

i成为一个列表。您的i变量是文本文件中的一行。你知道吗

你也许能做到

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

相关问题 更多 >

    热门问题