如何查找字符串在文本文件中出现的次数?

How to find the number of times a string occurs in a text file?

我正在尝试计算字符串在字符串文件中出现的次数。

data=open('xyz.txt')
num=[]
    while 1:
        numrow=[]
        count=0
        x=data.readline()
        if x=='':
            break
        for line in data:
            if line==x:
                count+=1
        numrow.append(x)
        numrow.append(count)
        num.append(numrow)
    print(num)

当我尝试上面的代码时,我总是得到错误的计数。另外,我无法获取每个字符串及其出现的次数。相反,我在第一行得到的字符串计数错误。

有没有办法打印所有不同的字符串及其相应的计数?

您可以使用collections.Counter

例如:

from collections import Counter

result = Counter()
with open('xyz.txt') as infile:
    for line in infile:
        result += Counter(line.strip().split())
print(result)  
from collections import Counter
with open('xyz.txt') as f:
    result = Counter(f.read().split())
print(result)

这里是可能对你有帮助的代码...

with open('xyz.txt') as f:
    k=f.read().split()
result={}
for element in k:
    if element not in result:
        result[element]=1
    else:
        result[element]+=1
print(result)
print(max(result)) #find max occurance string

经过一些试验,我发现了以下内容:

file = open("xyz.txt", 'r')
count = 0
inline = []
toFind = input("What should I find? > ")
toFind2 = toFind + '\n'
for line in file.readlines():
    line = line.split(' ')
    if toFind in line:
        count += 1
        inline.append("".join(line))
    if toFind2 in line:
        count += 1
        inline.append("".join(line))

print("This was found: " + str(count) + " times.")

这应该可以解决问题。 =]