文本预处理:分词、停用词处理、TF-IDF 向量化 (Python 实现)
文本预处理:分词、停用词处理、TF-IDF 向量化 (Python 实现)
本文将介绍如何使用 Python 对文本进行预处理,包括分词、停用词处理和 TF-IDF 向量化。
数据集:
假设给定一个数据集 corpus,文件地址为 'E:\Learning\大三下\自然语言处理\corpus',该数据集包含若干类数据,其目录结构为:
- neg: 包含若干个文本文件 (例如 1.txt, 2.txt ...)。
- pos: 包含若干个文本文件 (例如 1.txt, 2.txt ...)。
步骤:
-
加载停用词表:
可以使用哈工大停用词表,也可以使用其他停用词表。以下代码示例使用哈工大停用词表:
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) -
文本分词和停用词处理:
可以使用
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) -
文本向量化:
可以使用
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)
代码解释:
- 首先加载停用词表,使用
load_stopwords函数实现。 - 然后定义
preprocess_text函数,用于对单个文本进行分词和停用词处理,返回处理后的文本字符串。 - 接着遍历数据集,对每个文本文件进行分词和停用词处理,将处理后的文本字符串和标签存入
texts和labels列表中。 - 最后使用
sklearn库的TfidfVectorizer类对texts列表中的文本进行向量化,返回稀疏矩阵X和标签列表y。
总结:
本文介绍了如何使用 Python 对文本进行预处理,包括分词、停用词处理和 TF-IDF 向量化,并提供了完整的代码示例和解释。您可以根据自己的需求修改代码,例如使用不同的分词工具或向量化方法。
原文地址: https://www.cveoy.top/t/topic/oc3T 著作权归作者所有。请勿转载和采集!