Python为每个唯一的单词显示一行

2024-09-27 07:27:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个python代码来计算文本文件中每个单词的频率。代码应该为每个唯一的单词显示一行。我写的代码显示重复的单词。你知道吗

import string

text = open('mary.txt','r')
textr = text.read()

for punc in string.punctuation:
    textr = textr.replace(punc, "")

wordlist = textr.split()

for word in wordlist:
    count = wordlist.count(word)
    print word,':',count

我的电流输出是。。。你知道吗

are : 1
around : 1
as : 1
at : 2
at : 2
away : 1
back : 1
be : 2
be : 2
because : 1
below : 1
between : 1
both : 1
but : 1
by : 2
by : 2

输出应该只显示at : 2be : 2by : 2一次。我应该在我的代码中做些什么来实现这一点?你知道吗


Tags: 代码textinforstringbycountbe
3条回答

作为实现这一点的另一种方法,您可以采用您的解决方案,将所有条目作为(word,count)元组添加到一个集合中,然后打印该集合。您可能应该像@smarx指出的那样重新考虑您的实现,但这将使用您的本机代码解决问题。你知道吗

代码的问题是,您正在创建一个包含所有单词的列表,然后循环使用它们。您希望创建某种只存储唯一单词的数据结构。一个dict是一个很好的方法,但是在Python中有一个专门的集合叫做Counter,它就是为了这个目的而构建的。你知道吗

尝试一下(未经测试):

from collections import Counter
import string

text = open('mary.txt','r')
textr = text.read()

for punc in string.punctuation:
    textr = textr.replace(punc, "")

counts = Counter(textr.split())

for word, count in counts.items():
    print word,':',count

您可以尝试以下方法:

import string

frequency = {}
text = open('mary.txt','r')
textr = text.read()

for punc in string.punctuation:
    textr = textr.replace(punc, "")

wordlist = textr.split()

for word in wordlist:
    count = frequency.get(word,0)
    frequency[word] = count + 1

frequency_list = frequency.keys()

for words in frequency_list:
    print words,':', frequency[words]

相关问题 更多 >

    热门问题