python统计指定词频
时间: 2023-07-03 16:17:53 浏览: 46
你可以使用Python中的collections模块来统计指定词频。具体实现步骤如下:
1. 将文本读入内存
2. 使用split()方法将文本分割成单词列表
3. 使用collections模块中的Counter类统计单词出现的次数
4. 输出指定单词的出现次数
这里是一个简单的代码示例:
```
from collections import Counter
# 读入文本
with open('text.txt', 'r') as f:
text = f.read()
# 将文本分割成单词列表
words = text.split()
# 使用Counter类统计单词出现的次数
word_counts = Counter(words)
# 输出指定单词的出现次数
print(word_counts['指定单词'])
```
在上面的代码中,将文本读入内存后,使用split()方法将文本分割成单词列表,然后使用Counter类统计单词出现的次数。最后,使用字典的方式获取指定单词的出现次数。
相关问题
python中文词频统计
可以使用Python中的Jieba库来实现中文词频统计。首先需要将文本文件读取并分词,然后对每个词语进行计数,最后输出结果即可。
以下是示例代码:
```python
import jieba
filename = 'example.txt' # 假设需要统计的文本文件名为example.txt
# 读取文件并分词
with open(filename, 'r', encoding='utf-8') as f:
text = f.read()
words = jieba.lcut(text)
# 统计词频
word_counts = {}
for word in words:
if len(word) < 2: # 过滤掉长度小于2的词语,可根据实际需求调整
continue
if word not in word_counts:
word_counts[word] = 1
else:
word_counts[word] += 1
# 按词频排序并输出
sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
for word, count in sorted_word_counts:
print(word, count)
```
这段代码可以对指定的文本文件进行中文词频统计,并按照词频从高到低输出每个词语及其出现次数。
python读取文件统计词频
下面是一个简单的 Python 代码,它可以读取一个文本文件并统计每个单词出现的次数:
```python
import string
# 打开文件并读取内容
with open('filename.txt', 'r') as file:
text = file.read()
# 去除标点符号和换行符
text = text.translate(str.maketrans('', '', string.punctuation))
text = text.replace('\n', ' ')
# 将文本转换为小写字母
text = text.lower()
# 分割文本并统计单词出现的次数
word_counts = {}
for word in text.split():
if word not in word_counts:
word_counts[word] = 0
word_counts[word] += 1
# 输出结果
for word, count in sorted(word_counts.items(), key=lambda x: x[1], reverse=True):
print(f'{word}: {count}')
```
在这个代码中,我们首先打开指定的文件并读取它的内容。然后,我们使用 `translate()` 方法去除标点符号和换行符,并使用 `lower()` 方法将文本转换为小写字母。接下来,我们使用 `split()` 方法分割文本并统计每个单词出现的次数。最后,我们按照单词出现的次数排序并输出结果。