python - 使用 spacy 对 Pandas Dataframe 中的一列已解析的 html 文本进行词形还原

标签 python pandas apply spacy lemmatization

我想做一些非常琐碎的事情,但很难编写实现它的函数。对于 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 列中的一个句子/文本,en_core(x) 将从中创建一个文档,和 y 将代表每个标记,其中 y.lemma_ 产生词引理。 "".join(...) 会将找到的所有 lemms 连接到一个以空格分隔的字符串中。

关于python - 使用 spacy 对 Pandas Dataframe 中的一列已解析的 html 文本进行词形还原,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62712963/

相关文章:

python - 映射两个数据框的列并从列表中添加值

python - Pandas DataFrame Apply 函数,多个参数

r 按子组计算多个列的所有因子水平的频率

python - 是否可以在不替换变量的情况下加载 jinja2 模板?

Python - 重新排列 3D 数组中的元素

python - 选择目录后,QtGui.QFileDialog.getExistingDirectory() 窗口不会关闭(PyQt)

r - 如何将频率分布转换为 R 中的概率分布

Python库路径

python - 如何使用 python pandas groupby 或 .DataFrameGroupBy 对象创建唯一的组合列表

python - 使用 [key :value] combination in Python 将多列合并为一个列列表