自然语言处理文本预处理:分词、停用词处理和 TF-IDF 向量化

本文将介绍自然语言处理中常见的文本预处理方法,包括分词、停用词处理和 TF-IDF 向量化,并使用 Python 代码演示如何实现这些方法。

数据集结构

假设我们有一个数据集 corpus,其文件地址为 'E:\Learning\大三下\自然语言处理\corpus',该数据集包含若干类数据,其目录结构如下所示:

neg:
  1.txt
  2.txt
  ...
pos:
  1.txt
  2.txt
  ...

代码实现

import os
import jieba
from sklearn.feature_extraction.text import TfidfVectorizer

# 读取停用词表
def read_stopwords(file_path):
    stopwords = set()
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            stopwords.add(line.strip())
    return stopwords

# 预处理文本
def preprocess(file_path, stopwords):
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    # 分词
    words = jieba.cut(content)
    # 去除停用词
    words = [word for word in words if word not in stopwords]
    # 拼接词语
    return ' '.join(words)

# 构建文本向量
def build_vector(corpus_path, stopwords_path):
    # 读取停用词表
    stopwords = read_stopwords(stopwords_path)
    # 构建文本列表和标签列表
    corpus = []
    labels = []
    for label in os.listdir(corpus_path):
        label_path = os.path.join(corpus_path, label)
        for file in os.listdir(label_path):
            file_path = os.path.join(label_path, file)
            # 预处理文本
            content = preprocess(file_path, stopwords)
            corpus.append(content)
            labels.append(label)
    # 构建 TF-IDF 向量
    vectorizer = TfidfVectorizer()
    X = vectorizer.fit_transform(corpus)
    return X, labels

# 示例
corpus_path = r'E:\Learning\大三下\自然语言处理\corpus'
stopwords_path = r'E:\Learning\大三下\自然语言处理\stopwords.txt'
X, labels = build_vector(corpus_path, stopwords_path)

代码解释

  • read_stopwords 函数用于读取停用词表,返回一个停用词的集合。
  • preprocess 函数用于预处理文本,包括分词、去除停用词等操作,返回一个字符串。
  • build_vector 函数用于构建文本向量,包括读取数据集、预处理文本、构建 TF-IDF 向量等操作,返回一个稀疏矩阵和一个标签列表。

示例

在示例中,我们给定了数据集路径和停用词表路径,调用 build_vector 函数生成文本向量。

总结

本文介绍了自然语言处理中常见的文本预处理方法,包括分词、停用词处理和 TF-IDF 向量化,并使用 Python 代码演示了如何实现这些方法。这些方法可以有效地将文本数据转换为机器可读的格式,为后续的自然语言处理任务奠定基础。

自然语言处理文本预处理:分词、停用词处理和 TF-IDF 向量化

原文地址: https://www.cveoy.top/t/topic/ocZI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录