2015-09-14 33 views
-2

我有以下字符串:从字符串创建一个字典,其中的值是来自每个单词的元音计数?

S = "to be or not to be, that is the question?" 

我希望能够创建具有的

{'question': 4, 'is': 1, 'be,': 1, 'or': 1, 'the': 1, 'that': 1, 'be': 1, 'to': 1, 'not': 1} 

从哪里获得元音数量在每个字旁的字输出字典,而不是每个单词本身的数量。到目前为止,我有:

{x:y for x in S.split() for y in [sum(1 for char in word if char.lower() in set('aeiou')) for word in S.split()]} 

与输出:

{'or': 4, 'the': 4, 'question?': 4, 'be,': 4, 'that': 4, 'to': 4, 'be': 4, 'is': 4, 'not': 4} 

我如何从一个字符串一本字典,其中值是元音从每个字计数?

+0

'{ '告诉':1, '我':1, '什么':1, 'I':1, '告诉':1, '你,': 2,'to':1,'you':2}'不是一个有效的字典,因为那里有多个键。 –

+1

Nikki,欢迎来到StackOverflow我不认为这是一个-6的问题,所以我upvoted它。将来,试着明确地分开你的问题,并以问题的形式陈述它,这样你就不会再接受这个接收。如果你接受一个答案,它会给你加两个给你的代表。干杯。我会尽力帮助你在这里重申这个问题。 –

回答

-1

您可以使用re(正则表达式模块)来查找所有有效字(\w+ - 不包括空格和逗号),并使用Counter检查频率:

import re 

from collections import Counter 
s = "tell me what I tell you, to you" 
print Counter(re.findall(r'\w+', s)) 

输出

Counter({'you': 2, 'tell': 2, 'me': 1, 'what': 1, 'I': 1, 'to': 1}) 
+0

怪异downvote ...如果通过评论发布额外的反馈会更好。 – alfasin

1

单词旁边每个单词中的元音数目,而不是每个单词的数量它的数量自?

>>> s = "to be or not to be, that is the question" 

先删除标点符号:

>>> new_s = s.translate(None, ',?!.') 
>>> new_s 
'to be or not to be that is the question' 

然后分裂的空白:

>>> split = new_s.split() 
>>> split 
['to', 'be', 'or', 'not', 'to', 'be', 'that', 'is', 'the', 'question'] 

现在算在字典中的元音。注意,有没有多余的罪状:

>>> vowel_count = {i: sum(c.lower() in 'aeiou' for c in i) for i in split} 
>>> vowel_count 
{'be': 1, 'that': 1, 'is': 1, 'question': 4, 'to': 1, 'not': 1, 'the': 1, 'or': 1} 
相关问题