Python 从字符串创建字典,其中值是每个单词的元音计数?

Python 从字符串创建字典,其中值是每个单词的元音计数?,python,string,dictionary,Python,String,Dictionary,我有以下字符串: 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 fo

我有以下字符串:

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}
如何从值为每个单词元音计数的字符串中获取词典?

您可以使用(regex模块)查找所有有效单词(
\w+
-不包括空格和逗号),并使用检查频率:

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})
单词旁边每个单词的元音数,而不是每个单词本身的计数?

首先删除标点符号:

>>> 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}

{'tell':1,'me':1,'what':1,'I':1,'tell':1,'you':2,'to':1,'you':2}
不是有效的字典,因为里面有多次键。Nikki,欢迎来到StackOverflow。我认为这不是-6问题,所以我把它投了上一票。将来,尽量把你的问题清楚地分开,并以问题的形式陈述出来,这样你就不会再受到这样的接待了。如果你接受一个答案,它会给你加上两个给你的代表。干杯。我会尽力帮你重申这个问题。奇怪的否决票。。。如果通过评论发布额外的反馈会更好。
>>> 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}