要使用Python找出文本文件中的热词,你可以使用以下步骤:
1. 读取文本文件内容。
2. 使用分词工具对文本进行分词。
3. 统计分词后的词频。
4. 排序并输出出现频率最高的词汇。
下面是一个简单的示例代码,使用`jieba`库进行中文分词,并使用`collections.Counter`来统计词频:
```python
from collections import Counter
import jieba
读取文本文件
with open('example.txt', 'r', encoding='utf-8') as f:
text = f.read()
使用jieba分词
words = jieba.cut(text)
统计词频并排序
word_counts = Counter(words)
top_counts = word_counts.most_common(10) 输出前10个热词和它们的词频
输出前10个热词
print("前10个热词:")
for word, count in top_counts:
print(f"{word}: {count}")
如果你需要处理英文文本,并且希望使用逗号作为单词分隔符,你可以使用以下代码:
```python
from collections import Counter
读取文本文件
with open('2.txt', 'r') as f:
ll = f.read()
将空格都替换为逗号
ll = ll.replace(" ", ",")
防止由于文档编辑不规范出现双逗号的情况
ll = ll.replace(",,", ",")
分割文本为单词列表
l = ll.split("\n")
rows = []
dic = {}
for i in l:
row = i.split(",")
rows.append(row)
for ii in rows:
for each in ii:
if each in dic:
dic[each] += 1
else:
dic[each] = 1
输出所有的排序
print(sorted(dic.items(), key=lambda x: x, reverse=True))
只输出最大的值
HighValue = 0
HighKey = None
for each in dic:
if dic[each] > HighValue:
HighValue = dic[each]
HighKey = each
print(HighKey, HighValue)
请注意,这些代码示例可能需要根据你的具体需求进行调整。