无法从列表中读取要在ord中使用的字符()

时间:2014-04-11 08:19:32

标签: python

编写一个程序,提示用户输入文件名,打开文件进行阅读, 然后输出字母表中每个字符出现的次数。

#!/usr/local/bin/python

name=raw_input("Enter file name: ")
input_file=open(name,"r")
list=input_file.readlines()
count = 0
counter = 0


for i in range(65,91): #from A to Z
    for j in range(0,len(list)):
        if(i == ord(j)):   #problem: ord() takes j as an int here, I want it to get the char at j
            count = count + 1

    print i, count
    count = 0

for k in range(97,123): #from a to z
    for l in range(0,len(list)):
        if(k == ord(l)):  #problem: ord() takes l as an int here, I want it to get the char at l
            counter = counter + 1

    print k, counter
    count = 0

4 个答案:

答案 0 :(得分:0)

如果您只是想计算一个字母的频率,您可以这样做:

in_text = input_file.read()
frequencies = []

for i in range(65,91): #from A to Z
    frequencies.append(in_text.count(chr(i)))

print frequencies

答案 1 :(得分:0)

您可以使用此代码计算角色的时间。

#!/usr/local/bin/python

from collections import defaultdict

name=raw_input("Enter file name: ")
input_file=open(name,"r")
lines=input_file.readlines()

res = defaultdict(int)
for line in lines:
    for c in line:
        res[c] += 1

for k, v in res.items():
    print("%c %d" % (k , v))

答案 2 :(得分:0)

基于collections.Counter的另一个答案是差异。

from collections import Counter

filename = raw_input("Enter file name: ")
contents = open(filename, 'r').read()

frequencies = Counter()

for char in contents:
    if char.isalpha():
        frequencies[char] += 1

print frequencies.items()

答案 3 :(得分:0)

许多这类事情的答案是有人已经考虑过答案并放入标准库。

from collections import Counter

name=raw_input("Enter file name: ")
input_file=open(name,"r")
data = input_file.read()

c = Counter(data)

这可以获得所有角色的数量,而不仅仅是字母。获取角色

print(sorted(c))

获得3个最常见的

print(c.most_common(3))

如果您只想要过滤掉其他角色,则需要过滤掉其他角色。一种方法是使用生成器表达式。

import string
gen = (ch for ch in data if ch in string.ascii_lowercase)
c1 = Counter(gen)