【问题标题】:How can I print out the number of times each unique word appears in a inputted string?如何打印出每个唯一单词在输入字符串中出现的次数?
【发布时间】:2023-01-22 05:12:54
【问题描述】:

如何打印出每个唯一单词在输入字符串中出现的次数?我已经有了要运行的程序,以便打印出字符串中出现的唯一单词的数量。虽然,我想将它添加到其中,以便它打印出每个唯一单词在输入字符串中出现的次数。

喜欢:

“这里”这个词出现了6次

“网”字出现了7次

“你好”这个词出现了 5 次

等等

from collections import Counter
user_text = input("Please enter some text --> ")

def word_count(user_text):

    return(len(user_text.strip().split(" ")))

number_of_characters = len(user_text)

words = user_text.strip().split(' ')

print("You typed", len(user_text), "characters")
print("You typed", len(words), "words")
print("There are", len(set(words)), "unique words")
print("The word", words, "")

【问题讨论】:

    标签: python


    【解决方案1】:

    你似乎知道collections.Counter 但从来没有用它这是一种耻辱,因为它正是你所需要的。

    >>> from collections import Counter
    >>> Counter("hello world foo bar hello".split())
    Counter({'hello': 2, 'world': 1, 'foo': 1, 'bar': 1})
    >>> for word, count in Counter("hello world foo bar hello".split()).items():
    ...   print(f"The word '{word}' appeared {count} time(s)")
    ... 
    The word 'hello' appeared 2 time(s)
    The word 'world' appeared 1 time(s)
    The word 'foo' appeared 1 time(s)
    The word 'bar' appeared 1 time(s)
    

    【讨论】:

      猜你喜欢
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 2016-06-28
      • 2015-07-30
      • 2015-04-27
      • 2016-06-19
      • 1970-01-01
      相关资源
      最近更新 更多