首页 > 编程知识 正文

如何用Python统计词的个数

时间:2023-11-20 16:50:08 阅读:289459 作者:LWIE

Python 是一门非常流行的编程语言,其强大的字符串处理功能以及二十多个标准库使得在 Python 中完成字符串处理变成一件简单的事情,今天我们将探讨如何用 Python 统计词的个数。

一、使用 Python re 库实现

Python re 库是 Python 中用于正则表达式处理的一个标准库,通过正则表达式我们可以对文本中的内容进行处理。使用 Python re 库可以快速完成词频统计任务。

import re

input_str = "This is a test string. It contains several words that will be counted."

word_list = re.findall('w+', input_str.lower())
word_count = {}
for word in word_list:
    word_count[word] = word_count.get(word, 0) + 1

print(word_count)

在上面的代码中,使用 re 库中的 findall 函数可以匹配文本中的单词,并使用 Python 字典储存单词和词频。get 函数可以获取单词已经出现的词频,如果单词还未出现,则默认词频为 0。

二、使用 Python collections 库实现

Python collections 库是 Python 中使用最为广泛的库之一,提供了多种容器数据类型,可以用于高效地管理数据。

from collections import Counter

input_str = "This is a test string. It contains several words that will be counted."

word_list = input_str.lower().split()
word_count = Counter(word_list)

print(word_count)

在上面的代码中,使用 Python collections 库中的 Counter 函数可以快速统计每个单词在文本中出现的次数。

三、使用 Python NLTK 库实现

Python NLTK 库具有广泛的自然语言处理功能,包括分词、词性标注、命名实体识别等。本节我们将仅使用其中的分词功能完成词频统计任务。

首先需要安装 Python NLTK 库,可以通过 pip install nltk 命令进行安装。

import nltk
from nltk.tokenize import word_tokenize
from collections import Counter

nltk.download('punkt')

input_str = "This is a test string. It contains several words that will be counted."

word_list = word_tokenize(input_str.lower())
word_count = Counter(word_list)

print(word_count)

在上面的代码中,使用 Python NLTK 库中的 word_tokenize 函数可以将文本进行分词,然后再使用 Python collections 库中的 Counter 函数进行词频统计。

四、使用 Python pandas 库实现

Python pandas 库是 Python 中专业的数据处理库,可以在大数据量的情况下高效地完成数据处理工作。

首先需要安装 Python pandas 库,可以通过 pip install pandas 命令进行安装。

import pandas as pd

input_str = "This is a test string. It contains several words that will be counted."

df = pd.DataFrame({'words': input_str.lower().split()})
word_count = df['words'].value_counts().to_dict()

print(word_count)

在上面的代码中,使用 Python pandas 库中的 DataFrame 函数可以将文本进行分词,然后再使用 value_counts 函数进行词频计算,最后使用 to_dict 将词频结果转换为字典格式。

总结

本文介绍了如何使用 Python 进行词频统计,并介绍了四种不同的实现方式,分别是 Python re 库、Python collections 库、Python NLTK 库以及 Python pandas 库。不同的实现方式有不同的优势,开发者可以根据实际应用场景进行选择。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。