从字典里数单词?

2024-05-01 21:19:26 发布

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

我的职责应该是:

  • 一个参数作为tweet。
    • 这个tweet可以包含数字、单词、标签、链接和标点符号。你知道吗
  • 第二个参数是一个字典,它统计包含tweets的字符串中的单词,而不考虑其中包含的hashtag、提及、链接和标点符号。你知道吗

该函数返回字典中所有单个单词的小写字母,不带任何标点符号。你知道吗

如果tweet有Don't,那么字典会把它算作dont。你知道吗

我的职责是:

    def count_words(tweet, num_words):
''' (str, dict of {str: int}) -> None
Return a NoneType that updates the count of words in the dictionary.

>>> count_words('We have made too much progress', num_words)
>>> num_words
{'we': 1, 'have': 1, 'made': 1, 'too': 1, 'much': 1, 'progress': 1}
>>> count_words("@utmandrew Don't you wish you could vote? #MakeAmericaGreatAgain", num_words)
>>> num_words
{'dont': 1, 'wish': 1, 'you': 2, 'could': 1, 'vote': 1}
>>> count_words('I am fighting for you! #FollowTheMoney', num_words)
>>> num_words
{'i': 1, 'am': 1, 'fighting': 1, 'for': 1, 'you': 1} 
>>> count_words('', num_words)
>>> num_words
{'': 0}
'''

Tags: ofyou参数字典链接count单词num
1条回答
网友
1楼 · 发布于 2024-05-01 21:19:26

我可能误解了你的问题,但如果你想更新词典,你可以这样做:

d = {}
def update_dict(tweet):   
    for i in tweet.split():
        if i not in d:
            d[i] = 1
        else:
            d[i] += 1   
    return d

相关问题 更多 >