
在自然语言处理(nlp)任务中,文本预处理是至关重要的一步,它直接影响后续模型训练的效果和性能。然而,当我们在pandas dataframe中处理文本数据时,常常会遇到一个核心挑战:不同预处理函数对输入数据类型(字符串或字符串列表)的要求不一致,导致 attributeerror 等类型错误。例如,str.split() 方法只能应用于字符串,而不能应用于列表。理解数据在不同处理阶段的类型变化,并采取相应的处理策略,是构建健壮高效预处理管道的关键。
在构建文本预处理流程时,一个常见的错误是将分词(Tokenization)操作过早地应用于DataFrame列,导致列中的每个单元格从单个字符串变为一个单词列表。此后,如果继续使用期望字符串作为输入的函数(例如 contractions.fix()、unidecode() 或 re.sub()),就会引发 AttributeError: 'list' object has no attribute 'split' 等错误。
正确的处理方式是,一旦数据被分词成列表,后续所有针对单个单词的操作都必须通过遍历列表中的每个单词来完成。这意味着需要将操作封装在列表推导式中,如 [func(word) for word in x],其中 x 是一个单词列表。
为了解决上述问题并构建一个类型安全的文本预处理管道,我们需要仔细规划每个步骤,并确保函数能够正确处理当前数据类型。
首先,导入所需的Python库和NLTK资源。
import pandas as pd
import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.corpus import wordnet
from nltk.tokenize import word_tokenize
import re
import string
from unidecode import unidecode
import contractions
from textblob import TextBlob # 注意:TextBlob可能需要单独安装
# nltk.download('punkt')
# nltk.download('stopwords')
# nltk.download('wordnet')
# nltk.download('averaged_perceptron_tagger')词形还原通常需要词性(Part-of-Speech, POS)信息以获得更准确的结果。由于我们的数据在经过分词后将是单词列表,我们需要一个能够接受单词列表并对每个单词进行POS标记和词形还原的辅助函数。
def lemmatize_words(words_list, lemmatizer, pos_tag_dict):
"""
对单词列表进行POS标记并执行词形还原。
Args:
words_list (list): 待处理的单词列表。
lemmatizer (nltk.stem.WordNetLemmatizer): WordNet词形还原器实例。
pos_tag_dict (dict): NLTK POS标签到WordNet POS标签的映射字典。
Returns:
list: 词形还原后的单词列表。
"""
lemmatized_words = []
# 对整个单词列表进行POS标记,效率更高
pos_tuples = nltk.pos_tag(words_list)
for word, nltk_word_pos in pos_tuples:
# 获取WordNet对应的词性
wordnet_word_pos = pos_tag_dict.get(nltk_word_pos[0].upper(), None)
if wordnet_word_pos is not None:
new_word = lemmatizer.lemmatize(word, wordnet_word_pos)
else:
new_word = lemmatizer.lemmatize(word) # 默认动词
lemmatized_words.append(new_word)
return lemmatized_words这个函数将包含所有预处理步骤,并确保每一步都正确处理数据类型。
def processing_steps(df):
"""
对DataFrame中的文本列执行一系列NLP预处理步骤。
Args:
df (pd.DataFrame): 包含文本数据的DataFrame。
Returns:
pd.DataFrame: 预处理后的DataFrame。
"""
lemmatizer = WordNetLemmatizer()
# 定义NLTK POS标签到WordNet POS标签的映射
pos_tag_dict = {"J": wordnet.ADJ, "N": wordnet.NOUN, "V": wordnet.VERB, "R": wordnet.ADV}
# 初始化停用词列表
local_stopwords = set(stopwords.words('english'))
additional_stopwords = ["http", "u", "get", "like", "let", "nan"]
words_to_keep = ["i'", "i", "me", "my", "we", "our", "us"] # 确保这些词不会被移除
local_stopwords.update(additional_stopwords)
# 从停用词中移除需要保留的词
for word in words_to_keep:
if word in local_stopwords:
local_stopwords.remove(word)
new_data = {} # 用于存储处理后的数据
for column in df.columns:
# 复制原始列数据进行处理,避免直接修改原始DataFrame
results = df[column].copy()
# 1. 分词 (Tokenization)
# 将每个字符串单元格转换为单词列表
results = results.apply(word_tokenize)
# 从这里开始,'results' 中的每个元素都是一个单词列表。
# 因此,所有后续操作都需要通过列表推导式应用于列表中的每个单词。
# 2. 小写化 (Lowercasing each word within the list)
results = results.apply(lambda x: [word.lower() for word in x])
# 3. 移除停用词 (Removing stopwords)
# 移除非字母字符和停用词
results = results.apply(lambda tokens: [word for word in tokens if word.isalpha() and word not in local_stopwords])
# 4. 替换变音符号 (Replace diacritics)
# unidecode函数期望字符串输入,因此需要对列表中的每个单词应用
results = results.apply(lambda x: [unidecode(word, errors="preserve") for word in x])
# 5. 扩展缩写 (Expand contractions)
# contractions.fix期望字符串输入。这里假设每个“单词”可能包含缩写(如"don't"),
# 并且扩展后可能变成多个词(如"do not")。
# word.split()在这里是为了确保contractions.fix处理的是一个完整的短语,
# 并将可能产生的多个词重新组合。
results = results.apply(lambda x: [" ".join([contractions.fix(expanded_word) for expanded_word in word.split()]) for word in x])
# 6. 移除数字 (Remove numbers)
# re.sub期望字符串输入,对列表中的每个单词应用
results = results.apply(lambda x: [re.sub(r'\d+', '', word) for word in x])
# 7. 移除标点符号 (Remove punctuation except period)
# re.sub期望字符串输入,对列表中的每个单词应用
# 保留句号,因为它们可能用于句子的分割或表示缩写
results = results.apply(lambda x: [re.sub('[%s]' % re.escape(string.punctuation.replace('.', '')), '' , word) for word in x])
# 8. 移除多余空格 (Remove double space)
# re.sub期望字符串输入,对列表中的每个单词应用
results = results.apply(lambda x: [re.sub(' +', ' ', word).strip() for word in x]) # .strip()去除首尾空格
# 9. 词形还原 (Lemmatization)
# 使用我们自定义的lemmatize_words函数,它接受一个单词列表
results = results.apply(lambda x: lemmatize_words(x, lemmatizer, pos_tag_dict))
# 10. (可选) 拼写纠错 (Typos correction)
# TextBlob.correct() 通常在完整的句子或段落上表现更好。
# 如果在此阶段应用,它将对每个单词进行纠错,可能效果不佳或效率低下。
# 如果需要,可以考虑在分词前进行,或在所有处理完成后将词列表重新连接成字符串再进行。
# results = results.apply(lambda x: [str(TextBlob(word).correct()) for word in x])
# 将处理后的列存入新字典
new_data[column] = results
# 将处理后的数据转换为新的DataFrame
new_df = pd.DataFrame(new_data)
return new_df示例用法:
# 创建一个示例DataFrame
data = {
'title': ["Don't you love NLP?", "This is an amazing article about ML. I've read it 10 times."],
'body': ["It's really cool. I'm learning a lot. https://example.com", "The author is great! He doesn't skip anything."]
}
df = pd.DataFrame(data)
print("原始DataFrame:")
print(df)
# 执行预处理
processed_df = processing_steps(df.copy()) # 传入副本,避免修改原始df
print("\n预处理后的DataFrame:")
print(processed_df)以上就是Pandas DataFrame中NLP文本预处理的正确顺序与类型处理的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号