我正在创建一个读取文件的程序,并打印出它包含的每个单独字母的数量(如果有的话)。如果文件中包含“hello world”,我希望它打印1h,1e,3l,2o,1w,1r,1l等。这不是一个工作项目或任何东西,我这样做是出于兴趣。我似乎无法找到一个示例代码来执行此操作,这就是为什么我以为我会问这里:)想知道我的代码应该是什么样的。
a1 = 0
b1 = 0
c1 = 0
d1 = 0
e1 = 0
f1 = 0
g1 = 0
h1 = 0
i1 = 0
j1 = 0
k1 = 0
l1 = 0
m1 = 0
n1 = 0
o1 = 0
p1 = 0
q1 = 0
r1 = 0
s1 = 0
t1 = 0
u1 = 0
v1 = 0
w1 = 0
x1 = 0
y1 = 0
z1 = 0
with open("song.txt") as f:
for line in f:
if line == "a" or line == "A":
a1 = a1 + 1
if line == "b" or line == "B":
b1 - b1 + 1
if line == "c" or line == "C":
c1 = c1 + 1
if line == "d" or line == "D":
d1 = d + 1
if line == "e" or line == "e":
e1 = e1 + 1
if line == "f" or line == "F":
f1 = f1 + 1
if line == "g" or line == "G":
g1 = g1 + 1
if line == "h" or line == "H":
h1 = h1 + 1
if line == "i" or line == "I":
i1 = i1 + 1
if line == "j" or line == "J":
j1 = j1 + 1
if line == "k" or line == "K":
k1 = k1 + 1
if line == "l" or line == "L":
l1 = l1 + 1
if line == "m" or line == "M":
m1 = m1 + 1
if line == "n" or line == "N":
n1 = n1 + 1
if line == "o" or line == "O":
o1 = o1 + 1
if line == "P" or line == "p":
p1 = p1 + 1
if line == "q" or line == "Q":
q1 = q1 + 1
if line == "r" or line == "R":
r1 = r1 + 1
if line == "S" or line == "s":
s1 = s1 + 1
if line == "T" or line == "t":
t1 = t1 + 1
if line == "u" or line == "U":
u1 = u1 + 1
if line == "v" or line == "V":
v1 = v1 + 1
if line == "w" or line == "W":
w1 = w1 + 1
if line == "x" or line == "X":
x1 = x1 + 1
if line == "y" or line == "Y":
y1 = y1 + 1
if line == "z" or line == "Z":
z1 = z1 + 1fwef
print(a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1,m1,n1,o1,p1,q1,r1,s1,t1,u1,v1,w1,x1,y1,z1)
答案 0 :(得分:3)
这将:
打印每个字符及其出现次数。
from collections import Counter
with open('song.txt') as f:
count = Counter(f.read().lower())
keys = list(count)
keys.sort()
for x in keys:
print '{0}: {1} times'.format(x, count[x])
答案 1 :(得分:0)
试试这个...这将分别计算大写和小写字母。
import string
fp=open('song.txt','r')
file_list=fp.readlines()
freqs = {}
for line in file_list:
for char in line:
line=filter(lambda x:x in strings.letters, line.lower())
if char in freqs:
freqs[char] += 1
else:
freqs[char] = 1
for item in freqs:
print item, freqs[item]
或者只在小写字母的for循环后将行转换为小写。
答案 2 :(得分:0)
你的方法可能会有一些修改,但它真的很难处理(更不用说容易出错了)。你可能想要做的是使用一个名为 dictionary 的Python数据结构,它将一个键(一个字母)与一个值(count)相关联。所以你可以这样做:
letters = {}
with open("song.txt") as f:
for c in f.read():
c = c.lower()
if "a" <= c <= "z":
if c not in letters:
letters[c] = 0
letters[c] += 1
for c, n in sorted(letters.items()):
print("{0}{1}".format(c, n))
请注意f.read()
将整个文件读入内存,然后for c in f.read()
循环分别遍历每个字符。如果您只计算字符数,则无需将文件分成几行。
这是Python中的常见模式,你会发现有一个名为Counter
的标准库实用程序可以完成大部分工作(此处的另一个答案显示了如何使用它)。