问题
问题是这样的,一个词频统计的练习
相关代码
def get_txt():
txt = open('sentence.txt','rt').read()
txt = txt.lower()
return txt
s_txt = get_txt()
wordset = s_txt.split()
yalp = ['a','e','i','o','u']
counts = {}
for word in wordset:
for alp in word:
if alp in yalp:
counts[word] =counts.get(word,0) + 1
items = list(counts.items())
items.sort(key = lambda x:x[1],reverse = False)
for i in range(5):
word ,counts = items[i]
print('{0:<10}{1:>5}'.format(word ,counts))
运行结果及报错内容
Traceback (most recent call last):
word ,counts = items[i]
IndexError: list index out of range
only 1
我想要达到的结果
运行结果却报错了,上网搜了一圈仍然没有解决,可以帮忙看看吗
另外
1.对于下面这行有更优化的方法吗(感觉很蠢)
for word in wordset:
for alp in word:
if alp in yalp:
2.这行是抄的,对于为什么lambda要这么用不是很理解
items.sort(key = lambda x:x[1],reverse = False)
求解答!