[英]More efficient way to replace special chars with their unicode name in pandas df
[英]More efficient way to preprocess large amount of text in a pandas df?
我在下面的text_preprocessing()
函数中组织了一系列文本预处理步骤。 (还有更多内容,例如转换表情符号、删除标点符号等,为了清楚起见,我删除了这些内容。)
import spacy
nlp_model = spacy.load('en_core_web_lg')
nlp_model.add_pipe("merge_entities")
def text_preprocessing(text, lemmatizer):
text = text.lower()
text = " ".join([lemmatizer.lemmatize(w) for w in text.split()])
text = [w if not re.search(r'[^\x00-\x7F]', w) else "<FOREIGN>" for w in text.split()]
text = [w.text if (not w.ent_type_ or w.ent_type_ == 'PERSON' or w.ent_type_ == 'ORG')
else f"<{w.ent_type_}>" for w in nlp_model(" ".join(text))]
text = " ".join(text)
text = re.sub(r"<\s([A-Z]+?)", r"<\1", text)
text = re.sub(r"([A-Z]+?)\s>", r"\1>", text)
text = re.sub(r"\s(<[A-Z]+?)\s", r" \1> ", text)
text = re.sub(r"\s([A-Z]+?>)\s", r" <\1 ", text)
text = " ".join([w.upper() if ("<" in w and ">" in w) else w for w in text.split()])
return text
目前,我有一个工作解决方案如下:
from nltk.stem import WordNetLemmatizer
lmtzr = WordNetLemmatizer()
df['Preprocessed'] = df['Text'].apply(lambda x: text_preprocessing(x, lmtzr))
我已经将WordNetLemmatizer
的实例化移到text_preprocessing()
之外, text_preprocessing()
实例作为参数传递。 现在我正在考虑进一步优化此代码,因为要运行的消息数据库已显着增加,现在接近 30,000 行(30,000 个文本要预处理,而且数量每天都在增加)。 逐一文本预处理已经花费了大量时间。 我之前尝试过multiprocessing.Process
但没有产生太大影响。 我阅读了有关矢量化的内容,但不确定如何将其应用于我的情况。 我也知道外部的包,显然更容易建立多重处理df.apply()
如swifter
的模块,但是我希望能加快速度有点超过2-4次,因为我已经有相当多的数据,将来会更多。
可以使用以下函数创建示例数据:
import pandas as pd
import numpy as np
import random
def generate_example_data(rows=100):
df = pd.DataFrame(np.random.randint(0,100,size=(rows, 4)), columns=list('ABCD'))
df['Text'] = pd.Series(["".join([random.choice("aábcčdeëfghijklmnoópqrsştuvwxyz ") for i in range(random.randint(25,400))]) for j in range(rows)])
return df
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.