用python读取一个文件,统计某个特定字符串出现的次数,并将其保存在某个文件中。使用collections模块,统计字符串出现次数,选用模块中的Counter,返回字符串:次数的字典,可对字典打印,直接输出,或排序后输出。
import collections
file = open('E:/Anaconda/wejian/125.txt')
str = file.read().split(' ') #出现"of","the"等
#将文件以字符串读出 并以空格分解
n = collections.Counter(str)#返回字典"of":"16"等
print(n['of'])#打印n字典中,"of"键的值16
#第一种输出,直接打印字典
z = ""
for key,vlaue in n.items():
z += ("{0}{1}\n".format(key,n[key]))
with open('E:/Anaconda/wejian/126.txt','w') as output:
y = output.write(z)
#第二种输出,排序后输出
#s = zip(n.values(),n.keys())
#output = open('E:/Anaconda/wejian/126.txt','w')
#for item in sorted(s,reverse=True):
# output.write("{0}{1}\n".format(item[1],item[0]))