关于字频统计程序的改错
新手求助,一个字频统计的改错题问题要求:
读取“论语.txt”文件,统计文件中出现的字符出现次数,统计结果以字符.字符次数形式表示,将前100个最常用字符输出保存到“论语-字符统计.txt”文件中。
因为是个程序改错题, 只能修改语句中错误不能添加或者删除行,谢谢各位大神!
贴代码:file_name="论语.txt"
fi = open(file_name, "r", encoding="utf-8")
fo = open(file_name+"-字符统计.txt", "w", encoding="utf-8")
txt = fi.readline()
d = {}
for c in txt:
d=d.get(c,0)+1
del d['\n']
ls = list(d.items())
ls.sort(key=lambda x:x, reverse=True)
for i in range(100):
ls = "{}:{}".format(ls, ls)
fo.write(",".join(ls[:100]))
fi.close()
fo.close() 个人觉得应该把readline改成readlines,字典添加项那里应该也有一些错误,具体应该怎么改呢{:10_277:} file_name = "论语.txt"
fi = open(file_name)
fo = open(file_name + "-字符统计.txt" , "w")
txt = fi . read()
fi . close()
d = {}
for line in txt:
for c in line . strip():
d . setdefault(c , 0)
d += 1
ls = list(d.items())
ls.sort(key=lambda x:x, reverse=True)
for i in range(len(ls)):
ls = "{}:{}".format(ls, ls)
fo . write("" . join(ls[:len(ls)]))
fo.close()
页:
[1]