简介:本文是一篇针对NLP中文本预处理的完整教程,涵盖数据清洗、分词、词干提取、停用词处理等核心步骤,结合代码示例与实用技巧,帮助开发者构建高效的数据预处理流程。
在自然语言处理(NLP)任务中,文本预处理是连接原始数据与模型输入的桥梁。其质量直接影响模型训练效率与最终性能。本文将从数据清洗、分词与词形还原、停用词处理、向量化等核心环节展开,结合代码示例与行业实践,提供一套可落地的预处理方案。
原始文本常包含HTML标签、特殊符号、重复字符等噪声。例如,从网页抓取的文本可能包含<div>标签或冗余的空格。
处理步骤:
re库移除非文本字符
import retext = "<div>Hello, World!!</div>"clean_text = re.sub(r'<[^>]+>', '', text) # 移除HTML标签clean_text = re.sub(r'[^\w\s]', '', clean_text) # 移除标点
<UNK>)替代。中文分词:需解决无空格分隔的问题。常用工具包括:
import jiebatext = "我爱自然语言处理"seg_list = jieba.lcut(text) # 精确模式
英文分词:基于空格与标点分割,但需处理缩写(如”U.S.”)与连字符(如”state-of-the-art”)。NLTK的word_tokenize是常用选择:
from nltk.tokenize import word_tokenizetext = "NLP is fascinating!"tokens = word_tokenize(text)
from nltk.stem import PorterStemmerstemmer = PorterStemmer()print(stemmer.stem("running")) # 输出: run
from nltk.stem import WordNetLemmatizerlemmatizer = WordNetLemmatizer()print(lemmatizer.lemmatize("better", pos="a")) # 输出: good
停用词(如”的”、”is”)通常携带低信息量。可选用:
实现示例:
from nltk.corpus import stopwordsstop_words = set(stopwords.words('english'))filtered_tokens = [word for word in tokens if word.lower() not in stop_words]
from sklearn.feature_extraction.text import TfidfVectorizercorpus = ["This is a sentence.", "Another example sentence."]vectorizer = TfidfVectorizer()X = vectorizer.fit_transform(corpus)
将文本表示为词频向量,忽略顺序信息。
from sklearn.feature_extraction.text import CountVectorizervectorizer = CountVectorizer()X = vectorizer.fit_transform(corpus)
import gensim.downloader as apiwv = api.load("glove-wiki-gigaword-100") # 加载100维GloVe向量print(wv["computer"].shape) # 输出: (100,)
使用textblob库自动修正拼写错误:
from textblob import TextBlobtext = "I havv a good speling!"corrected_text = str(TextBlob(text).correct())
通过WordNet或领域词典将同义词映射为统一形式(如”car”→”automobile”)。
langdetect识别文本语言。
from langdetect import detectprint(detect("Ceci est un texte français.")) # 输出: fr
multiprocessing加速分词与向量化。文本预处理是NLP项目的“地基”,其精细化程度直接决定模型上限。本文从基础清洗到高级向量化提供了全流程指导,开发者可根据任务需求灵活组合技术栈。未来,随着少样本学习与多模态预处理的发展,预处理环节将进一步融合自动化与领域适配能力。