#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)))
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?
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))
要计算特定单词在文本文件中出现的次数,请将文本文件的内容读取为字符串,并使用string.count()函数将单词作为参数传递给count()函数。
语法:
其中word是字符串,count()返回该字符串中出现的单词数
因此,您可以读取该文件并使用count()方法
希望这会很好
注: 您甚至可以循环遍历每个单词并递增计数器。但是使用像Python这样的高级编程语言,使用这种内置方法将是有益的
一个示例解决方案:
animalpoem.txt
程序输出:
台阶
相关问题 更多 >
编程相关推荐