“”“
这是一段读取文件,统计文件中相同字母出现的频率的代码,然后在屏幕输出,虽然能统计相同字符的出现频率,但大写和小写系统
还是认为是2个字母,谁能指点一下,还有最好用lambda函数来表达同一个字符出现的频率
”“”
from os import strerror
counters = {chr(ch): 0 for ch in range(ord('a'), ord('z') + 1)}
print(counters)
file_name = input("Enter the name of the file to analyze: ")
try:
f = open("textfile.txt", "rt")
for line in f:
for char in line:
if char.isalpha():
char.lower()
x=set(line)
f.close()
for item in x:
counters[item]=line.count(item.lower())
cnt=counters[item]
if cnt > 0:
print(item, '->',cnt)
except IOError as e:
print("I/O error occurred: ", strerror(e.errno))
"""
output:
输入cbaBaa
输出
a -> 3
c -> 1
b -> 2
将字符全部转换为大写或者小写
“”“
这是一段读取文件,统计文件中相同字母出现的频率的代码,然后在屏幕输出,虽然能统计相同字符的出现频率,但大写和小写系统
还是认为是2个字母,谁能指点一下,还有最好用lambda函数来表达同一个字符出现的频率
”“”
from os import strerror
counters = {chr(ch): 0 for ch in range(ord('a'), ord('z') + 1)}
print(counters)
file_name = input("Enter the name of the file to analyze: ")
try:
f = open("textfile.txt", "rt")
for line in f:
for char in line:
if char.isalpha():
char.lower()
x=set(line)
f.close()
for item in x:
str=item.lower()
counters[str]=line.count(str)
cnt=counters[str]
if cnt > 0:
print(str, '->',cnt)
except IOError as e:
pass
使用lambda函数改写:
from os import strerror
counters = {chr(ch): 0 for ch in range(ord('a'), ord('z') + 1)}
print(counters)
file_name = input("Enter the name of the file to analyze: ")
try:
f = open(file_name, "rt")
for line in f:
line=line.strip().lower()
for char in line:
if char.isalpha():
x=set(line)
f.close()
c=list(map(lambda a:line.count(a),x))
for a,c in zip(x,c):
print(a+":"+str(c))
except IOError as e:
print("I/O error occurred: ", strerror(e.errno))
运行结果:
{'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0, 'g': 0, 'h': 0, 'i': 0, 'j': 0, 'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0, 'p': 0, 'q': 0, 'r':
0, 's': 0, 't': 0, 'u': 0, 'v': 0, 'w': 0, 'x': 0, 'y': 0, 'z': 0}
Enter the name of the file to analyze: textfile.txt
c:1
a:3
b:2
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!