python:如何读取文件中出现的字符
我想显示文本文件中每个字母出现的次数python:如何读取文件中出现的字符,python,count,Python,Count,我想显示文本文件中每个字母出现的次数 f=file.read() for i in f: if str(i) == '\n': pass else: print("There are ",f.count(i),str(i),"'s in the text.") 这不是很好,因为我得到了n个符号出现的n个文本副本。我该怎么办 谢谢 尝试使用计数器。但是你可以用零初始化字母字典,并计算频率。让我们考虑一个快速的例子来说明这个想法。 import string letterCoun
f=file.read()
for i in f:
if str(i) == '\n':
pass
else:
print("There are ",f.count(i),str(i),"'s in the text.")
这不是很好,因为我得到了n个符号出现的n个文本副本。我该怎么办
谢谢 尝试使用计数器。但是你可以用零初始化字母字典,并计算频率。让我们考虑一个快速的例子来说明这个想法。
import string
letterCounter= dict(zip(string.ascii_lowercase,[0]*26))
data = '''\
I am trying to count words
file is compsed by lines
lines by words
words are composed by letters
'''
for line in data.splitlines():
for word in line.split():
for letter in list(word.lower()):
letterCounter[letter]+=1
print letterCounter
输出:
{'a': 2, 'c': 3, 'b': 3, 'e': 8, 'd': 5, 'g': 1, 'f': 1, 'i': 6, 'h': 0, 'k': 0, 'j': 0, 'm': 3, 'l': 4, 'o': 8, 'n': 4, 'q': 0, 'p': 2, 's': 9, 'r': 6, 'u': 1, 't': 5, 'w': 3, 'v': 0, 'y': 4, 'x': 0, 'z': 0}
要在文本文件上使用相同的代码,需要使用Open.读取文件
我找到了一个对我的任务很有效的解决方案:
x=0
while x<10000: ## or some sufficiently high number
if chr(x) == "\n":
x+=1
elif chr(x) in someFile:
print("There are ", f.count(chr(x)), chr(x),"'s in the text.")
x+=1
else:
x+=1
谢谢,工作很有魅力。虽然我只是在f中为字母做了:字母计数器[字母]+=1。i、 这不是如何使用计数器,也不是如何打开文件。您需要的只是c=Counterfile.read
x=0
while x<10000: ## or some sufficiently high number
if chr(x) == "\n":
x+=1
elif chr(x) in someFile:
print("There are ", f.count(chr(x)), chr(x),"'s in the text.")
x+=1
else:
x+=1