【问题标题】:Using spacy to lemmatize a column of parsed html text in a Pandas Dataframe使用 spacy 在 Pandas Dataframe 中对一列已解析的 html 文本进行词形还原
【发布时间】:2020-07-03 09:56:25
【问题描述】:

我想做一些非常微不足道的事情,但努力编写函数来完成它。对于 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['tokenized'].apply(lambda x: " ".join([y.lemma_ for y in en_core(x)]))
  • 成功了吗?预期的结果是什么?
  • 嘿,我收到了TypeError: Argument 'string' has incorrect type (expected str, got list)。但是,当我将列切换到未标记的原始文本(“tweet”)时,它可以工作。这让我现在很困惑,因为我认为词形还原应该在标记上执行,而不是在原始文本上。这是因为空间还是功能?到目前为止谢谢!
  • 实际上,我还在df["tweet"] 列上运行了我的测试,并且成功了。您需要在文本上运行它,而不是标记。

标签: python pandas apply spacy lemmatization


【解决方案1】:

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

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

这里,x 将是 tweet 列中的一个句子/文本,en_core(x) 将创建一个文档,y 将代表每个标记,y.lemma_ 产生单词 lemma。 " ".join(...) 会将找到的所有词元连接到一个以空格分隔的字符串中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2017-02-24
    相关资源
    最近更新 更多