【问题标题】:counting words from a dictionary?从字典中数单词?
【发布时间】:2016-12-01 16:12:09
【问题描述】:

我的功能应该有:

  • 一个参数作为推文。
    • 此推文可能涉及数字、单词、主题标签、链接和标点符号。
  • 第二个参数是一个字典,它用推文计算该字符串中的单词,而忽略其中包含的主题标签、提及、链接和标点符号。

该函数将字典中的所有单个单词作为小写字母返回,不带任何标点符号。

如果推文有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}
'''

【问题讨论】:

  • I am not sure if I am doing this functions correctly,我们不确定,因为我们看不到您做了什么并尝试了...为你写代码。我们回答具体问题,并且非常愿意帮助那些努力解决问题的人。
  • 哦,对不起,我的意思是如何为这个特定的函数写一个正确的返回语句!或者只是任何提示?
  • 再次阅读#MooingRawr 的评论。您的回复与您的原始帖子一样没有可用信息和有意义的问题。除非你能提出一个好的问题,否则你无法得到一个好的答案。

标签: python string dictionary twitter


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2015-07-27
    • 1970-01-01
    • 2022-12-09
    • 2019-10-09
    • 1970-01-01
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多