【问题标题】:Creating a dictionary from a string where the values are the vowel counts from each word?从字符串创建字典,其中值是每个单词的元音计数?
【发布时间】:2015-09-15 08:14:31
【问题描述】:

我有以下字符串:

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}

如何从字符串中获取字典,其中值是每个单词的元音计数?

【问题讨论】:

  • {'tell':1, 'me':1, 'what':1, 'I':1, 'tell':1, 'you,':2, 'to':1, 'you':2} 不是有效的字典,因为其中有多次键。
  • Nikki,欢迎来到 StackOverflow 我不认为这是一个 -6 的问题,所以我投了赞成票。以后,尽量把你的问题清楚地分开,并以问题的形式陈述出来,这样你就不会再得到这个接待了。如果您接受答案,它将给您的代表加 2。干杯。我会尽力帮你在这里重述这个问题。

标签: python string dictionary


【解决方案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}

【讨论】:

    【解决方案2】:

    您可以使用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})
    

    【讨论】:

    • 奇怪的反对票...如果可以通过评论发布额外的反馈会更好。
    猜你喜欢
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 2017-11-27
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多