从列表中提取单词,在文本文件中搜索它们,并对每个单词进行计数

2024-10-01 02:40:00 发布

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

我正在学习Python,目前我有一个文本文件。在该文本文件中,我想搜索列表中已有的单词['mice',parrot',],并计算mice和parrot被提及的次数。我现在有

enter code herewith open('animalpoem.txt', 'r') as animalpoemfile:
data = animalpoemfile.read()
search animals = ['mice', parrot']                               

Tags: txt列表dataascodeopen单词次数
3条回答

要计算特定单词在文本文件中出现的次数,请将文本文件的内容读取为字符串,并使用string.count()函数将单词作为参数传递给count()函数。

语法:

n = String.count(word)

其中word是字符串,count()返回该字符串中出现的单词数

因此,您可以读取该文件并使用count()方法

#get file object reference to the file
with open("file.txt", "r") as file:
    #read content of file to string
    data = file.read()

words = ['apple', 'orange']

for word in words:
    print('{} occurred {} times.'.format(word, data.count(word)))

希望这会很好

注: 您甚至可以循环遍历每个单词并递增计数器。但是使用像Python这样的高级编程语言,使用这种内置方法将是有益的

一个示例解决方案:

import re

animals = ['mice', 'parrot']

# make a dictionary with keys being the names of the animals,
# and values being initial counts (0)
counts = dict([(a, 0) for a in animals])

with open("animalpoem.txt") as f:
     for line in f:  # loop over lines of the file, assign to variable "line"
          for word in re.findall("\w+", line.lower()):  # convert to lower case and make list of words and then iterate over it
               if word in counts:  # tests if the word is one of the keys in the dictionary
                    counts[word] += 1  # if so, increments the count value associated with that word

print(counts)

animalpoem.txt

Three blind mice. Three blind mice.
See how they run. See how they run.
They all ran after the farmer's wife,
Who cut off their tails with a carving knife,
Did you ever see such a sight in your life,
As three blind mice?

程序输出:

{'mice': 3, 'parrot': 0}

台阶

  1. 打开文件
  2. 读取文件并存储在变量中
  3. 计算要在此变量中搜索的单词数
    def num_of_word_in_file(file_name, word):
      with open(file_name) as file:
        content = file.read()
      return content.count(word)
    for animal in animals :
        print(num_of_word_in_file(file_name, animal))
    

相关问题 更多 >