no pain, no gain, where there is a will, there is a way 如何用python算词的频次
时间: 2024-05-05 12:20:01 浏览: 49
要用 Python 算出一段文本中每个单词出现的频次,可以按照如下步骤进行:
1. 将文本中的所有单词提取出来,并且将它们全部转换成小写字母,方便后续统计。
可以使用正则表达式对文本进行分词,代码如下:
```
import re
text = "No pain, no gain. Where there is a will, there is a way."
words = re.findall(r'\b\w+\b', text.lower())
```
2. 遍历单词列表,统计每个单词出现的次数。
可以使用一个字典来存储每个单词出现的次数,代码如下:
```
word_freq = {}
for word in words:
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1
```
3. 输出每个单词和它的频次。
可以使用一个循环遍历字典中的每一项,依次输出单词和它的频次,代码如下:
```
for word, freq in word_freq.items():
print(f"{word}: {freq}")
```
完整代码如下:
```
import re
text = "No pain, no gain. Where there is a will, there is a way."
words = re.findall(r'\b\w+\b', text.lower())
word_freq = {}
for word in words:
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1
for word, freq in word_freq.items():
print(f"{word}: {freq}")
```
阅读全文