文本预处理:分词、停用词处理、TF-IDF 向量化 (Python 实现)

本文将介绍如何使用 Python 对文本进行预处理,包括分词、停用词处理和 TF-IDF 向量化。

数据集:

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

  • neg: 包含若干个文本文件 (例如 1.txt, 2.txt ...)。
  • pos: 包含若干个文本文件 (例如 1.txt, 2.txt ...)。

步骤:

  1. 加载停用词表:

    可以使用哈工大停用词表,也可以使用其他停用词表。以下代码示例使用哈工大停用词表:

    stopwords_path = 'stopwords.txt'
    
    def load_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
    
    stopwords = load_stopwords(stopwords_path)
    
  2. 文本分词和停用词处理:

    可以使用 jieba 库进行中文分词,对于英文文本可以使用 nltk 库进行分词。以下代码示例展示中文文本分词:

    import jieba
    
    def preprocess_text(text, stopwords):
        words = jieba.cut(text)
        words = [word for word in words if word not in stopwords]
        return words
    
    text = '这是一段测试文本'
    preprocessed_text = preprocess_text(text, stopwords)
    print(preprocessed_text)
    
  3. 文本向量化:

    可以使用 sklearn 库的 TfidfVectorizer 类实现 TF-IDF 向量化。以下代码示例展示完整的预处理过程,包括分词、停用词处理和 TF-IDF 向量化:

    import os
    import jieba
    from sklearn.feature_extraction.text import TfidfVectorizer
    
    stopwords_path = 'stopwords.txt'
    
    def load_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_text(text, stopwords):
        words = jieba.cut(text)
        words = [word for word in words if word not in stopwords]
        return ' '.join(words)
    
    corpus_path = 'E:\Learning\大三下\自然语言处理\corpus'
    
    stopwords = load_stopwords(stopwords_path)
    texts = []
    labels = []
    for label in os.listdir(corpus_path):
        label_path = os.path.join(corpus_path, label)
        for file_name in os.listdir(label_path):
            file_path = os.path.join(label_path, file_name)
            with open(file_path, 'r', encoding='utf-8') as f:
                text = f.read()
                preprocessed_text = preprocess_text(text, stopwords)
                texts.append(preprocessed_text)
                labels.append(label)
    
    vectorizer = TfidfVectorizer()
    X = vectorizer.fit_transform(texts)
    y = labels
    
    print(X.toarray())
    print(y)
    

代码解释:

  1. 首先加载停用词表,使用 load_stopwords 函数实现。
  2. 然后定义 preprocess_text 函数,用于对单个文本进行分词和停用词处理,返回处理后的文本字符串。
  3. 接着遍历数据集,对每个文本文件进行分词和停用词处理,将处理后的文本字符串和标签存入 texts 和 labels 列表中。
  4. 最后使用 sklearn 库的 TfidfVectorizer 类对 texts 列表中的文本进行向量化,返回稀疏矩阵 X 和标签列表 y。

总结:

本文介绍了如何使用 Python 对文本进行预处理,包括分词、停用词处理和 TF-IDF 向量化,并提供了完整的代码示例和解释。您可以根据自己的需求修改代码,例如使用不同的分词工具或向量化方法。

文本预处理:分词、停用词处理、TF-IDF 向量化 (Python 实现)

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

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