如何计算文本文件中的字母数?
下面的代码统计名为"alice_in_enderland.txt"的文本文件中的字母数
到目前为止,我只有文本:AAAAA bbbb CCCC
在文本文件中:
选择 | 换行 | 行号
- # countletters.py
- def display(i):
- if i == 10: return 'LF'
- if i == 13: return 'CR'
- if i == 32: return 'SPACE'
- return chr(i)
- infile = open('alice_in_wonderland.txt', 'r')
- text = infile.read()
- infile.close
- counts = 128* [0]
- for letter in text:
- counts[ord(letter)]+=1
- outfile =open('alice_counts.dat','w')
- outfile.write("-12s%s\n" % ("Character","Count"))
- outfile.write("====================\n")
- for i in range(len(counts)):
- if counts[i]:
- outfile.write("%-12s%d\n" % (display(i), counts[i]))
- outfile.close()
当我运行这段代码时,我得到错误:
选择 | 换行 | 行号
- Traceback (most recent call last):
- File "countletters.py", line 15, in <module>
- counts[ord(letter)]+=1
- IndexError: list index out of range
尽管这个例子直接来自于《如何像计算机科学家一样思考》一书中的《如何使用Python2版学习》一书。有人能帮我找出这个代码出了什么问题吗?
最新情况:
当我使用以下位置提供的alice_in_exedland.txt文本文件运行代码时:
Http://openbookproject.net/thinkcs/p...sh2e/ch10.html
我得到一个不同的错误:
选择 | 换行 | 行号
- File "countletters.py", line 18, in <module>
- outfile.write("-12s%s\n" % ("Character","Count"))
- TypeError: not all arguments converted during string formatting