首页 > 解决方案 > 在Python中查找单词的频率和按降序排列的频率

问题描述

我试图在 .txt 文件中查找单词的频率,并通过对每个单词的出现次数进行排序来丰富它。

到目前为止,我完成了 %90 的任务。剩下的就是按降序对出现的次数进行排序。

这是我的代码:

def frequency_check(lines):
    print("Frequency of words in file")
    words = re.findall(r"\w+", lines)
    item_list = []

    for item in words:
        if item not in item_list:
            item_count = words.count(item)
            print("{} : {} times".format(item, item_count))
            item_list.append(item)


with open("original-3.txt", 'r') as file1:
    lines = file1.read().lower()
    frequency_check(lines)

这是我在其中找到词频的 .txt 文件,

在此处输入图像描述

这是我得到的输出:

Frequency of words in file
return : 2 times
all : 1 times
non : 1 times
overlapping : 1 times
matches : 3 times
of : 5 times
pattern : 3 times
in : 4 times
string : 2 times
as : 1 times
a : 3 times
list : 3 times
strings : 1 times
the : 6 times
is : 1 times
scanned : 1 times
left : 1 times
to : 1 times
right : 1 times
and : 1 times
are : 3 times
returned : 1 times
order : 1 times
found : 1 times
if : 2 times
one : 2 times
or : 1 times
more : 2 times
groups : 2 times
present : 1 times
this : 1 times
will : 1 times
be : 1 times
tuples : 1 times
has : 1 times
than : 1 times
group : 1 times
empty : 1 times
included : 1 times
result : 1 times
unless : 1 times
they : 1 times
touch : 1 times
beginning : 1 times
another : 1 times
match : 1 times

Process finished with exit code 0

将这些和输出从出现次数最高到最低进行排序将是一个巨大的挑战。

PS:我考虑过使用字典,但是,字典是不可变的,我不能对它们使用排序方法

有任何想法吗?

非常感谢

标签: python

解决方案


我同意@lolu,您应该使用字典,但如果您仍想使用 a list,这里有一个解决方案:

import re


def frequency_check(lines):
    print("Frequency of words in file")
    words = re.findall(r"\w+", lines)
    unique_words = set(words)
    item_list = []

    for item in unique_words:
        item_count = words.count(item)
        item_list.append((item, item_count))

    item_list.sort(key=lambda t: (t[1], t[0]), reverse=True)
    for item, item_count in item_list:
        print("{} : {} times".format(item, item_count))


with open("original-3.txt", 'r') as file1:
    lines = file1.read().lower()
    frequency_check(lines)

并且使用更好的实现collections.Counter

import re
from collections import Counter


def frequency_check(lines):
    print("Frequency of words in file")
    words = re.findall(r"\w+", lines)
    word_counts = Counter(words)
    for item, item_count in word_counts.most_common():
        print("{} : {} times".format(item, item_count))


with open("original-3.txt", 'r') as file1:
    lines = file1.read().lower()
    frequency_check(lines)

推荐阅读