如何使用 Python 3.3 计算词频并按出现次数排序

Barbara Streisand
发布: 2024-10-21 21:40:03
原创
858 人浏览过

How to Count Word Frequencies and Sort by Occurrence Using Python 3.3

计算单词频率并按出现次数排序

正如您所提到的,您的目标是建立两个列表:一个用于不同的单词,另一个用于不同的单词它们各自的频率,单词按频率升序排列。您已经提供了该方法的概要,但让我们使用 Python 3.3 填写详细信息。

由于 Python 3.3 不包含计数器或字典等内置机制,因此我们将使用一个简单的循环来达到期望的结果。

<code class="python"># Create lists to store unique words and their counts
unique_words = []
frequencies = []

# Iterate over the original list of words
for word in original_list:
    # Check if the word is already in the unique words list
    if word not in unique_words:
        # If not, add the word to the unique words list and initialize its frequency to 1
        unique_words.append(word)
        frequencies.append(1)
    else:
        # If the word is already in the list, increment its frequency
        frequencies[unique_words.index(word)] += 1

# Sort the unique word list based on the frequencies list
sorted_words = [word for _, word in sorted(zip(frequencies, unique_words), reverse=True)]

# Output the sorted list of unique words
print(sorted_words)</code>
登录后复制

此代码有效地计算单词频率并对唯一单词进行相应排序,以唯一单词的排序列表形式提供输出。

以上是如何使用 Python 3.3 计算词频并按出现次数排序的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!