用Python输出一个字符串中出现次数最多的单词和出现次数最少的单词及其出现次数
时间: 2023-07-14 19:14:02 浏览: 40
可以使用 Python 的 Counter 对象来实现此功能。代码如下:
```python
from collections import Counter
def count_words(s):
# 将字符串转化为小写,并去除标点符号和换行符
s = s.lower().replace('\n', '').translate(str.maketrans('', '', '.,?!'))
# 将字符串分割成单词,并计算每个单词出现的次数
words = s.split()
word_count = Counter(words)
# 获取出现次数最多的单词和出现次数最少的单词
most_common_word, most_common_count = word_count.most_common(1)[0]
least_common_word, least_common_count = word_count.most_common()[-1]
return (most_common_word, most_common_count), (least_common_word, least_common_count)
# 示例:
s = "Hello, world! This is a test. Hello, Python. Python is fun."
print(count_words(s)) # (('hello', 2), ('test', 1))
```
在上面的代码中,我们首先将输入字符串转化为小写,并去除标点符号和换行符。然后,我们使用 Python 的 Counter 对象计算每个单词出现的次数。最后,我们使用 Counter 对象的 `most_common()` 方法获取出现次数最多的单词和出现次数最少的单词。