首页 > 解决方案 > 从文本文件计算词频,但我的输出中有错误

问题描述

从文件中读取所有行并使用 split() 方法将这些行拆分为单词。strip("""!"#$%&'()*,-./:;?@[]_""")此外,使用方法调用从单词末尾删除标点符号

我是python的初学者并试图解决一些基本问题,我在给出的问题中使用了split和strip函数,但是我在某些单词的频率上出现错误,请查看我的代码。

蟒蛇代码:

def word_frequencies(filename="alice.txt"):

    with open(filename) as f:
        string=f.read()

    words=string.split()

    l=[]

    for word in words:
        temp=word.strip("""!"#$%&'()*,-./:;?@[]""")

        if temp:
            l.append(temp)


    string2=[]

    for i in l:
        if i not in string2:
            string2.append(i)

    for j in string2:
        print(f"{j}\t{l.count(j)}")

输出:

The 64 

Project 83

Gutenberg   27

EBook   3

of  303

. . . 等等。

但实际输出是:

The     64

Project 83

Gutenberg   26

EBook   3

of      303

. . . 等等

标签: pythonpython-3.xdata-analysis

解决方案


使用re.findall拆分为单词:

from re import findall

words = findall(r"\b\w+\b", text)

,其中text是您的f.read()

然后数一数:

from collections import Counter

c = Counter(words)

检查字数:

for word in ("The", "Project", "Gutenberg", "EBook",):
    print(word, c[word])

印刷:

The 64
Project 83
Gutenberg 83
EBook 3

推荐阅读