python使用正则表达式统计字符串中出现次数最多的单词的代码
时间: 2023-11-28 07:22:16 浏览: 94
同样可以使用Python的正则表达式模块re和collections模块来实现字符串中出现次数最多的单词的统计。
下面是一个示例代码:
```python
import re
from collections import Counter
# 定义要匹配的正则表达式
pattern = r'\b\w+\b'
# 定义待匹配的字符串
text = 'This is a test sentence. This is another test sentence.'
# 使用正则表达式找出所有单词,并统计出现次数
cnt = Counter(re.findall(pattern, text))
# 找到出现次数最多的单词
most_common_word = cnt.most_common(1)[0][0]
print(f"The most common word is: {most_common_word}")
```
输出结果为:
```
The most common word is: This
```
这个代码使用了正则表达式找出字符串中的所有单词,并使用collections模块中的Counter类进行统计。最后,通过Counter类的most_common方法找到出现次数最多的单词。
相关问题
python统计一段字符串中单词出现的次数
可以通过正则表达式和Python内置的collections模块来实现统计字符串中单词出现的次数。
代码示例:
```python
import re
from collections import Counter
string = 'This is a sample string for counting words in Python. This string is just a sample.'
words = re.findall(r'\w+', string.lower())
word_counts = Counter(words)
print(word_counts)
```
输出结果:
```
Counter({'this': 2, 'is': 2, 'a': 2, 'sample': 2, 'string': 2, 'for': 1, 'counting': 1, 'words': 1, 'in': 1, 'python': 1, 'just': 1})
```
首先,使用正则表达式 `\w+` 匹配字符串中的单词,并将单词全部转换为小写。然后使用 collections 模块的 Counter 函数统计单词出现的次数。最后输出结果即可。
给出一个字符串s,统计s中出现单词的次数
可以使用正则表达式和字典来实现统计单词出现的次数。具体步骤如下:
1. 使用正则表达式将字符串s中的单词提取出来,可以使用re.findall()函数实现。
2. 遍历提取出来的单词列表,使用字典记录每个单词出现的次数。
3. 最后输出每个单词出现的次数即可。
下面是实现代码:
```python
import re
def count_words(s):
# 使用正则表达式提取单词
words = re.findall(r'\b\w+\b', s)
# 使用字典记录单词出现的次数
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 输出单词出现的次数
for word, count in word_count.items():
print(word, count)
# 测试代码
s = "hello world, hello python, python is a good language"
count_words(s)
```
输出结果为:
```
hello 2
world 1
python 2
is 1
a 1
good 1
language 1
```
注意,这里使用了\b来匹配单词边界,确保只匹配单词而不是单词的一部分。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)