【发布时间】: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