如何计算文本文件中的字母数?

下面的代码统计名为"alice_in_enderland.txt"的文本文件中的字母数
到目前为止,我只有文本:AAAAA bbbb CCCC
在文本文件中:

选择 | 换行 | 行号
  1. # countletters.py
  2.  
  3. def display(i):
  4.     if i == 10: return 'LF'
  5.     if i == 13: return 'CR'
  6.     if i == 32: return 'SPACE'
  7.     return chr(i)
  8.  
  9. infile = open('alice_in_wonderland.txt', 'r')
  10. text = infile.read()
  11. infile.close
  12.  
  13. counts = 128* [0]
  14. for letter in text:
  15.     counts[ord(letter)]+=1
  16. outfile =open('alice_counts.dat','w')
  17. outfile.write("-12s%s\n" % ("Character","Count"))
  18. outfile.write("====================\n")
  19. for i in range(len(counts)):
  20.         if counts[i]:
  21.             outfile.write("%-12s%d\n" % (display(i), counts[i]))
  22. outfile.close()
  23.  

当我运行这段代码时,我得到错误:

选择 | 换行 | 行号
  1. Traceback (most recent call last):
  2.   File "countletters.py", line 15, in <module>
  3.     counts[ord(letter)]+=1
  4. IndexError: list index out of range
  5.  

尽管这个例子直接来自于《如何像计算机科学家一样思考》一书中的《如何使用Python2版学习》一书。有人能帮我找出这个代码出了什么问题吗?
最新情况:
当我使用以下位置提供的alice_in_exedland.txt文本文件运行代码时:
Http://openbookproject.net/thinkcs/p...sh2e/ch10.html
我得到一个不同的错误:

选择 | 换行 | 行号
  1.   File "countletters.py", line 18, in <module>
  2.     outfile.write("-12s%s\n" % ("Character","Count"))
  3. TypeError: not all arguments converted during string formatting
  4.  
# 回答1


现在,这似乎适用于给定的文本文件和给定的代码,没有明显的原因。不确定为什么我会收到上面的错误。
# 回答2


U在"-12s%s\n"之前缺少%符号,应该类似于"%-12s%s\n"
看,原因是..。U传递两个参数来编写它,因为%不在那里,它被视为字符串,因此只有一个参数被转换为实际值。还有一个没有皈依..。
在PYTHON中,您将收到有意义的错误。试着理解这个错误..你可以解决任何事情..。

标签: python

添加新评论