新增函数,统计出现次数排名前3的单词,以及对应的出现次数,返回结果
时间: 2023-11-23 11:05:41 浏览: 32
可以使用 Python 中的 Counter 类来实现该功能。以下是一个示例代码:
```python
from collections import Counter
def top_3_words(text):
words = text.lower().split()
counter = Counter(words)
top_words = counter.most_common(3)
return top_words
```
该函数接收一个字符串作为输入,将字符串转换成小写字母后按空格分割成单词列表。然后使用 Counter 类创建一个单词计数器,最后返回出现次数排名前三的单词以及对应的出现次数。
你可以使用以下代码测试该函数:
```python
text = "Hello world hello world hello python"
top_words = top_3_words(text)
print(top_words)
```
输出结果应为:
```
[('hello', 3), ('world', 2), ('python', 1)]
```
其中每个元素为一个元组,第一个元素为单词,第二个元素为出现次数。
相关问题
新增函数,统计出现次数最多的字母,返回结果
好的,可以使用Python内置的collections模块中的Counter类来实现。以下是实现代码:
```python
from collections import Counter
def most_common_letter(string):
# 将字符串中的字母转换成小写,并过滤掉非字母字符
letters = [c.lower() for c in string if c.isalpha()]
# 使用Counter类统计字母出现次数
counter = Counter(letters)
# 获取出现次数最多的字母及其出现次数
most_common = counter.most_common(1)
if most_common:
return most_common[0]
else:
return None
```
在上面的代码中,我们首先通过列表推导式将字符串中的字母转换成小写,并过滤掉非字母字符。然后使用Counter类统计字母出现次数,再使用Counter类的most_common方法获取出现次数最多的字母及其出现次数。最后返回结果即可。
调用这个函数,可以得到如下结果:
```python
>>> most_common_letter("Hello, world!")
('l', 3)
>>> most_common_letter("The quick brown fox jumps over the lazy dog")
('o', 4)
>>> most_common_letter("12345")
None
```
需要注意的是,如果字符串中没有字母,函数将返回None。
word_frequency()函数统计并以字典类型返回每个单词出现的次数。
可以使用Python中的split()函数将字符串拆分成单词列表,然后使用字典来记录每个单词出现的次数。以下是一个示例函数:
```python
def word_frequency(text):
# 将文本拆分成单词列表
words = text.split()
# 创建一个空字典来存储单词出现的次数
freq_dict = {}
# 遍历单词列表,统计每个单词出现的次数
for word in words:
if word in freq_dict:
freq_dict[word] += 1
else:
freq_dict[word] = 1
# 返回字典
return freq_dict
```
使用示例:
```python
text = "this is a test test string for testing"
freq_dict = word_frequency(text)
print(freq_dict)
```
输出结果:
```
{'this': 1, 'is': 1, 'a': 1, 'test': 2, 'string': 1, 'for': 1, 'testing': 1}
```
这个函数可以统计任何文本中每个单词出现的次数。