python使用正则表达式统计字符串中出现次数最多的单词的代码
时间: 2023-11-28 12:22:16 浏览: 48
同样可以使用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 函数统计单词出现的次数。最后输出结果即可。
python统计字符串 s 中前 10 个高频单词的出现次数,将单词和次数写入 wordnum.txt 文件。
好的,以下是实现代码:
```python
# 导入必要的库
import re
from collections import Counter
# 定义要处理的字符串
s = "Hello world, hello python, hello AI, python is great, AI is awesome"
# 使用正则表达式将字符串拆分成单词列表
words = re.findall(r'\b\w+\b', s)
# 统计单词出现次数
word_counts = Counter(words)
# 获取前 10 个高频单词及其出现次数
top_words = word_counts.most_common(10)
# 将结果写入文件
with open('wordnum.txt', 'w') as f:
for word, count in top_words:
f.write(f'{word}: {count}\n')
```
在上述代码中,我们首先使用正则表达式将字符串 `s` 拆分成单词列表 `words`,然后使用 `collections` 库中的 `Counter` 类对单词进行计数,得到每个单词的出现次数。接着,我们使用 `most_common()` 方法获取前 10 个高频单词及其出现次数,并将结果写入文件 `wordnum.txt` 中。