我有一个文本文件,其中包括:
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我只是需要一些帮助,在计数部分,我将能够管理其余的。致以问候。
发布于 2017-04-17 10:36:13
你需要的是一本字典。
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)发布于 2017-04-17 10:32:54
使用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发布于 2017-04-17 10:33:16
使用in判断数组是否是另一个数组的元素,在Python中,可以使用字符串作为数组:
def countOccurence(l):
count = 0
#I'm stuck here#
if l in table:
count +=1
return counthttps://stackoverflow.com/questions/43449556
复制相似问题