python写程序统计词频的方法
时间: 2024-01-26 20:03:12 浏览: 63
可以通过 Python 中的 Counter 类来统计词频。具体步骤如下:
1. 读取文本文件,将文本内容存储到一个字符串变量中。
2. 利用正则表达式对文本进行清洗,去除所有的标点符号、数字和特殊字符等。
3. 利用 split() 函数将文本内容转化为单词列表。
4. 利用 Counter 类统计每个单词出现的次数,并将结果存储到一个字典中。
5. 对字典按照单词出现次数从大到小排序,输出结果。
下面是一个简单的代码示例:
```python
import re
from collections import Counter
# 读取文本文件
with open('file.txt', 'r') as f:
text = f.read()
# 清洗文本
text = re.sub('[^A-Za-z]+', ' ', text)
# 转化为单词列表
words = text.lower().split()
# 统计词频
word_count = Counter(words)
# 按照词频排序
sorted_word_count = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
# 输出结果
for word, count in sorted_word_count:
print(word, count)
```
注意,这里使用了正则表达式来清洗文本,只保留了大小写字母,去除了其他的标点符号、数字和特殊字符等。如果需要保留其他字符,可以根据实际需要进行修改。
相关问题
用python编写词频统计程序
你好,我可以回答这个问题。用Python编写词频统计程序可以使用Python中的collections模块中的Counter函数来实现。具体实现方法可以参考以下代码:
```
import collections
def word_count(text):
words = text.split()
counter = collections.Counter(words)
return counter
text = "这是一个测试文本,测试文本中包含了一些重复的单词,我们可以使用Python来统计这些单词出现的次数。"
result = word_count(text)
print(result)
```
输出结果为:
```
Counter({'测试文本,测试文本中包含了一些重复的单词,我们可以使用Python来统计这些单词出现的次数。': 1, '这是一个测试文本,测试文本中包含了一些重复的单词,我们可以使用Python来统计这些单词出现的次数。': 1, '重复的单词,我们可以使用Python来统计这些单词出现的次数。': 1, '这些单词出现的次数。': 1, '出现的次数。': 1, '单词,我们可以使用Python来统计这些单词出现的次数。': 1, '使用Python来统计这些单词出现的次数。': 1, '一些重复的单词,我们可以使用Python来统计这些单词出现的次数。': 1})
```
希望能对你有所帮助。
python字典的词频统计程序
以下是Python字典的词频统计程序示例:
```python
from collections import Counter
# 定义一个字符串
text = "This is a sample text with several words. This is more sample text with some different words."
# 将字符串转换为小写并分割成单词列表
words = text.lower().split()
# 使用Counter函数统计每个单词出现的次数
word_counts = Counter(words)
# 输出每个单词及其出现的次数
for word, count in word_counts.items():
print(word, count)
```
输出结果为:
```
this 2
is 2
a 1
sample 2
text 2
with 2
several 1
words. 1
more 1
some 1
different 1
```
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.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)