使用 spacy 对 Pandas 数据框中的一列已解析的 html 文本进行词形还原

Using spacy to lemmatize a column of parsed html text in a Pandas Dataframe

我想做一些非常琐碎的事情,但很难编写实现它的函数。对于 NLP 多类分类任务,我必须预处理 pandas DataFrame。感兴趣的列是已解析的 html 文本(列:“tweet”)。我规范化我的数据(小写,删除标点符号,停用词,...),然后我想使用 spacy 对其进行词形还原并将其作为列写回。但是,我不能把这个功能放在一起。我在 SO 上找到了几个示例,但它们都使用列表,我无法将其转换为 DF。因为我有一个非常大的 DataFrame (10GB),所以我想使用一个不太慢的函数。任何帮助或建议将不胜感激。谢谢:)

# My real text is in german, but since Englisch is more frequent I use "en_core_web_sm" here
import spacy
en_core = spacy.load('en_core_web_sm')

# Create DataFrame
pos_tweets = [('I love this car', 'positive'), ('This view is amazing', 'positive'), ('I feel great this morning', 'positive'), ('I am so excited about the concert', 'positive'), ('He is my best friend', 'positive')]
df = pd.DataFrame(pos_tweets)
df.columns = ["tweet","class"]

# Normalization
df['tweet'] = [entry.lower() for entry in df['tweet']]
# Tokenization
df["tokenized"] = [w.split() for w in df["tweet"]]

# Lemmatization
# This is where I struggle. I can't get together the English Model en_core, lemma_ and stuff :(
df["lemmatized"] = df['tokenized'].apply(lambda x: [en_core(y.lemma_) for y in x])

您需要 运行 在文本上,而不是标记上。

df["lemmatized"] = df['tweet'].apply(lambda x: " ".join([y.lemma_ for y in en_core(x)]))

在这里,x 将是 tweet 列中的一个 sentence/text,en_core(x) 将从中创建一个文档,而 y 将表示每个标记,y.lemma_ 产生词引理。 " ".join(...) 会将找到的所有 lemms 连接成一个 space 分隔的字符串。