首页  >  文章  >  后端开发  >  如何使用 Python 3.3 计算词频并按出现次数排序

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

Barbara Streisand
Barbara Streisand原创
2024-10-21 21:40:03837浏览

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn