用python输入程序:在给定的字符串中,包含多个相同的单词,统计出现两次以上的单词
时间: 2024-02-05 18:13:33 浏览: 26
可以使用 Python 的内置模块 `collections` 中的 `Counter` 类来实现:
```python
from collections import Counter
def count_duplicate_words(text):
words = text.split()
word_counts = Counter(words)
duplicate_words = [word for word, count in word_counts.items() if count > 1]
return duplicate_words
```
这个函数接受一个字符串作为参数,并返回出现两次以上的单词,以列表形式返回。我们首先将字符串分割成单词,然后使用 `Counter` 对象统计每个单词出现的次数。最后,我们遍历 `Counter` 对象中的每个键值对,找到出现次数大于 1 的单词,将其添加到 `duplicate_words` 列表中并返回。