string - python - 在文本文件中,如何查找字符串发生的次数?

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


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



这应该可以。

...