python:如何读取文件中出现的字符

时间:2014-11-06 23:56:19

标签: 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个重复的文本。我该怎么办?

谢谢!

2 个答案:

答案 0 :(得分:0)

我找到了一个适用于我的任务的解决方案:

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

答案 1 :(得分:-1)

尝试使用Counter。但是你可以初始化一个零字母字典,并计算频率。让我们考虑一个简单的例子来说明这个想法。

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

来阅读该文件
with open('filename.txt') as fp:
    for line in fp:
        for word in line.split():
            for letter in list(word):
                letterCounter[letter]+=1
print letterCounter