<p><strong>索引器错误:列表索引超出范围</strong>意味着您的某个索引试图访问列表之外的内容-您需要<a href="https://stackoverflow.com/questions/4929251/how-to-step-through-python-code-to-help-debug-issues">debug your code</a>来查找情况。在</p>
<hr/>
<p>使用<a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow noreferrer">collections.Counter</a>简化此任务:</p>
<pre><code># with open('corups.txt', 'r') as r: text = r.read()
text = """peter piper picked a peck of pickled peppers
a peck of pickled peppers peter piper picked
if peter piper picked a peck of pickled peppers
where s the peck of pickled peppers peter piper picked """
from collections import Counter
# split the text in lines, then each line into words and count those:
c = Counter( (x for y in text.strip().split("\n") for x in y.split()) )
# format the output
print(*(f"{cnt} {wrd}" for wrd,cnt in c.most_common()), sep="\n")
</code></pre>
<p>输出:</p>
^{pr2}$
<p>相关:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/20639180/explanation-of-how-nested-list-comprehension-works">Explanation of how nested list comprehension works?</a></li>
<li><a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow noreferrer">collections.Counter</a></li>
<li><a href="https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-literals" rel="nofollow noreferrer">formatted string literals (f-strings)</a></li>
</ul>