[英]Counting number of occurrence of a string in a text file
我有一个文本文件包含:
Rabbit:Grass
Eagle:Rabbit
Grasshopper:Grass
Rabbit:Grasshopper
Snake:Rabbit
Eagle:Snake
我想计算一个字符串的出现次数,比如,动物在文本文件中出现的次数并打印计数。 这是我的代码:
fileName = input("Enter the name of file:")
foodChain = open(fileName)
table = []
for line in foodChain:
contents = line.strip().split(':')
table.append(contents)
def countOccurence(l):
count = 0
for i in l:
#I'm stuck here#
count +=1
return count
我不确定python如何计算文本文件中的出现次数。 我想要的输出是:
Rabbit: 4
Eagle: 2
Grasshopper: 2
Snake: 2
Grass: 2
我只需要一些关于计数部分的帮助,我将能够管理剩下的部分。 问候。
使用str.split()
, re.sub()
函数和collections.Counter子类的解决方案:
import re, collections
with open(filename, 'r') as fh:
# setting space as a common delimiter
contents = re.sub(r':|\n', ' ', fh.read()).split()
counts = collections.Counter(contents)
# iterating through `animal` counts
for a in counts:
print(a, ':', counts[a])
输出:
Snake : 2
Rabbit : 4
Grass : 2
Eagle : 2
Grasshopper : 2
用in
判断是否数组是另一个数组的元素,在Python中,你可以使用一个字符串作为数组:
def countOccurence(l):
count = 0
#I'm stuck here#
if l in table:
count +=1
return count
你需要的是一本字典。
dictionary = {}
for line in table:
for animal in line:
if animal in dictionary:
dictionary[animal] += 1
else:
dictionary[animal] = 1
for animal, occurences in dictionary.items():
print(animal, ':', occurences)
from collections import defaultdict
dd = defaultdict(int)
with open(fpath) as f:
for line in f:
words = line.split(':')
for word in words:
dd[word] += 1
for k,v in dd.items():
print(k+': '+str(v))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.