Linux 拨号vps windows公众号手机端

python怎么对文本进行词频统计

lewis 8年前 (2017-04-28) 阅读数 7 #程序编程
文章标签 python

使用Python对文本进行词频统计可以使用下面的步骤:

  1. 打开文本文件并读取文本内容。
with open("text.txt", "r") as file:
    text = file.read()
  1. 对文本进行分词。
import re

# 去除标点符号和空白字符
text = re.sub(r'[^\w\s]', '', text)

# 将文本拆分为单词列表
words = text.split()
  1. 统计每个单词的出现次数。
from collections import Counter

word_count = Counter(words)
  1. 排序并输出词频结果。
for word, count in word_count.most_common():
    print(word, count)

完整的代码如下:

import re
from collections import Counter

with open("text.txt", "r") as file:
    text = file.read()

text = re.sub(r'[^\w\s]', '', text)
words = text.split()
word_count = Counter(words)

for word, count in word_count.most_common():
    print(word, count)

请确保将代码中的"text.txt"替换为实际的文本文件路径。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门