2015-11-05 111 views
1

我想创建一个文本中所有唯一字词的字典。关键是单词,值是这个词的频率创建文本字词典

dtt = ['you want home at our peace', 'we went our home', 'our home is nice', 'we want peace at home'] 
word_listT = str(' '.join(dtt)).split() 
wordsT = {v:k for (k, v) in enumerate(word_listT)} 
print wordsT 

我希望这样的事情:

{'we': 2, 'is': 1, 'peace': 2, 'at': 2, 'want': 2, 'our': 3, 'home': 4, 'you': 1, 'went': 1, 'nice': 1} 

不过,我收到这样的:

{'we': 14, 'is': 12, 'peace': 16, 'at': 17, 'want': 15, 'our': 10, 'home': 18, 'you': 0, 'went': 7, 'nice': 13} 

很显然,我滥用功能或做错事。

请帮助

回答

3

的问题,你在做什么是你在存储这里所说的是不是那些话的计数的数组索引。

要做到这一点,你可以只使用collections.Counter

from collections import Counter 

dtt = ['you want home at our peace', 'we went our home', 'our home is nice', 'we want peace at home'] 
counted_words = Counter(' '.join(dtt).split()) 
# if you want to see what the counted words are you can print it 
print counted_words 

>>> Counter({'home': 4, 'our': 3, 'we': 2, 'peace': 2, 'at': 2, 'want': 2, 'is': 1, 'you': 1, 'went': 1, 'nice': 1}) 

一些清理:在评论中提到

str()是不必要的你' '.join(dtt).split()

您还可以删除列表中的分配并在同一行上做你的计数器

Counter(' '.join(dtt).split()) 

有关您的列表索引的更多细节;首先你必须了解你的代码在做什么。

dtt = [ 
    'you want home at our peace', 
    'we went our home', 
    'our home is nice', 
    'we want peace at home' 
] 

注意,这里有19个单词; print len(word_listT)回报19.现在在word_listT = str(' '.join(dtt)).split()您做的所有的单词列表的下一行,它看起来像这样

word_listT = [ 
    'you', 
    'want', 
    'home', 
    'at', 
    'our', 
    'peace', 
    'we', 
    'went', 
    'our', 
    'home', 
    'our', 
    'home', 
    'is', 
    'nice', 
    'we', 
    'want', 
    'peace', 
    'at', 
    'home' 
] 

再数一数:19个字。最后一个字是'家'。并且列表索引从0开始,因此0到18 = 19个元素。 yourlist[18]是'家'。这与字符串位置或任何内容无关,只是新数组的索引。 :)

+0

很好用!谢谢! – Toly

+0

@当然是!很高兴我能帮上忙!你应该看看周围的集合,那里有很多有用的工具。“计数器”是一个,我也一直使用'defaultdict'。如果你有任何问题随时问,我会尽力帮助,如果我可以:) –

+0

@JohnRuddell join()返回一个字符串,你为什么要把它转换为字符串?计数器(''.join(dtt).split())会做 – helloV

1

试试这个:

from collections import defaultdict 

dtt = ['you want home at our peace', 'we went our home', 'our home is nice', 'we want peace at home'] 
word_list = str(' '.join(dtt)).split() 
d = defaultdict(int) 
for word in word_list: 
    d[word] += 1 
0

enumerate返回一个单词列表与他们的指标,不符合他们的频率。也就是说,当您创建单词T字典时,每个v实际上是k的最后一个实例的word_listT中的索引。要做你想做的事,使用for循环可能是最直接的。

wordsT = {} 
for word in word_listT: 
    try: 
     wordsT[word]+=1 
    except KeyError: 
     wordsT[word] = 1