描述:
参考课本P173实例代码10.2,统计小说《哈姆雷特》(文件:hamlet.txt)中一些主要人物名字出现的次数。
需统计次数的人物名字:hamlet,claudius,gertrude,polonius,ophelia,laertes,horatio,rosencrantz,guildenstern,marcellus。
输入:
无
输出:
注意:输出如上图,按递减顺序输出统计结果,且名字左对齐、设定输出宽度15,统计次数右对齐、设定输出宽度2;打开文件hamlet.txt使用语句open(“hamlet.txt”, “r”,encoding=“utf-8”).read()。
name_dict = {
'hamlet': 0,
'claudius': 0,
'gertrude': 0,
'polonius': 0,
'ophelia': 0,
'laertes': 0,
'horatio': 0,
'rosencrantz': 0,
'guildenstern': 0,
'marcellus': 0
}
def getText():
txt = open('hamlet.txt', 'r', encoding='utf-8').read()
txt = txt.lower()
for ch in '!"#$%&()*+,-./:;<=>?@[\n]^_`{|}~':
txt = txt.replace(ch, ' ')
return txt
words = getText().split(' ')
for word in words:
if word in name_dict:
name_dict[word] += 1
name_dict = sorted(list(name_dict.items()), key=lambda item: item[1], reverse=True)
for item in name_dict:
print('{:<15}{:>2}'.format(item[0], item[1]))