计算文本文件中字符串的出现次数

时间:2017-04-17 10:19:30

标签: python count

我有一个包含以下内容的文本文件:

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

我只需要一些关于计数部分的帮助,我将能够管理剩下的部分。问候。

4 个答案:

答案 0 :(得分:0)

使用//get rod of containerView offset edgesForExtendedLayout = [] //move tab buttonBarView.frame.origin.y = buttonBarView.frame.origin.y + 30 str.split()函数和collections.Counter子类的解决方案:

re.sub()

输出:

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

答案 1 :(得分:0)

使用ID判断数组是否是另一个数组的元素,在Python中,您可以使用字符串作为数组:

in

答案 2 :(得分:0)

你需要的是一本字典。

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)

答案 3 :(得分:0)

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