面试题[Python]-统计一篇英文文章中词频前十的词及对应数量

在做这道笔试题的时候, 面试官直接提示说可以使用Python内置库来做这道题. 下面的题解中会包含两种方案

题目

使用Python统计一篇文章中词频前十的词及其对应数量.

题解一

普通做法的话就是使用容器对象来记录单词及其计数, 然后再获取前十词频的词信息. 示例代码如下:

content = """The Zen of Python, by Tim PetersBeautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""
word_list = content.split()
actual_word_list = []
count_info = {}
for word in word_list:if word.isalpha():word.strip(".").strip(",").strip("!")actual_word_list.append(word)word_set = set(actual_word_list)
count_info = {word: actual_word_list.count(word) for word in word_set}result = sorted(count_info.items(), key=lambda item: item[1], reverse=True)[:10]print(result)

题解二

使用Python库collections的Counter对象进行统计, 非常简单, 如下所示:

from collections import Counterword_list = content.split()
actual_word_list = []
count_info = {}
for word in word_list:if word.isalpha():word.strip(".").strip(",").strip("!")actual_word_list.append(word)count = Counter(content.split())
print(count.most_common(10))


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部