读取年报文本文件,在年报文本文件中提取关键词词频,python代码
时间: 2023-04-01 21:00:31 浏览: 126
你好,以下是回答:
可以使用Python中的jieba库来提取关键词和词频。具体代码如下:
import jieba
from collections import Counter
# 读取年报文本文件
with open('annual_report.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用jieba库进行分词
words = jieba.cut(text)
# 统计词频
word_counts = Counter(words)
# 输出前10个出现频率最高的词
for word, count in word_counts.most_common(10):
print(word, count)
注意:需要先安装jieba库,可以使用pip install jieba命令进行安装。同时,需要将annual_report.txt替换成实际的年报文本文件名。
相关问题
Python文件 文本词频统计代码
以下是Python实现文本词频统计的代码:
```python
import re
# 定义函数,传入文件名和要统计的单词个数
def word_count(file_name, num):
# 打开文件
with open(file_name, 'r') as f:
# 读取文件内容
content = f.read()
# 将单词转换为小写,并去掉标点符号
words = re.findall(r'\b[a-z]+\b', content.lower())
# 统计单词出现的次数
word_dict = {}
for word in words:
if word not in word_dict:
word_dict[word] = 1
else:
word_dict[word] += 1
# 排序并输出结果
sorted_word_dict = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)
for i in range(num):
print(sorted_word_dict[i][0], sorted_word_dict[i][1])
# 调用函数进行测试
word_count('test.txt', 10)
```
代码解释:
1. `re.findall(r'\b[a-z]+\b', content.lower())` 用正则表达式匹配文件内容中的单词,`\b` 表示单词的边界,`[a-z]+` 表示一个或多个小写字母。
2. `word_dict` 用字典来保存单词出现的次数,如果单词不存在则添加到字典中,否则将出现次数加一。
3. `sorted_word_dict` 将字典按照值进行排序,`key=lambda x: x[1]` 表示按照值进行排序,`reverse=True` 表示降序排列。
4. `for i in range(num)` 只输出前面 num 个单词和出现次数。
文本文件的词频统计python代码实现
好的,以下是一个简单的 Python 代码实现文本文件的词频统计:
```python
import re
# 打开文件并读取内容
with open('filename.txt', 'r') as f:
text = f.read()
# 将文本中的标点符号和换行符替换为空格
text = re.sub(r'[^\w\s]', ' ', text)
# 将文本按空格分割成单词列表
words = text.split()
# 统计每个单词的出现次数
word_count = {}
for word in words:
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
# 输出词频统计结果
for word, count in word_count.items():
print(f'{word}: {count}')
```
需要替换一些特殊字符,例如标点符号和换行符,以便正确地计算单词数。然后,我们将文本拆分为单词列表,并遍历列表以计算每个单词的出现次数。最后,我们输出每个单词及其出现次数的结果。