数据帧 python 中的快速文本处理

Fast text processing in python on dataframe

我正在 python 处理电子商务数据。我已将该数据加载到 python 并将其转换为 pandas 数据框。现在我想对该数据执行文本处理,例如删除不需要的字符、停用词、词干提取等。目前我应用的代码运行良好,但需要花费大量时间。我有大约 200 万行数据要处理,处理它需要很长时间。我在 10,000 行上尝试了该代码,它花费了大约 240 秒。我是第一次从事此类项目。任何减少时间的帮助都会非常有帮助。

提前致谢。

from nltk.stem import PorterStemmer
from nltk.corpus import stopwords
import re

def textprocessing(text):
    stemmer = PorterStemmer()
    # Remove unwanted characters
    re_sp= re.sub(r'\s*(?:([^a-zA-Z0-9._\s "])|\b(?:[a-z])\b)'," ",text.lower())
    # Remove single characters
    no_char = ' '.join( [w for w in re_sp.split() if len(w)>1]).strip()
    # Removing Stopwords
    filtered_sp = [w for w in no_char.split(" ") if not w in stopwords.words('english')]
    # Perform Stemming
    stemmed_sp = [stemmer.stem(item) for item in filtered_sp]
    # Converting it to string
    stemmed_sp = ' '.join([x for x in stemmed_sp])
    return stemmed_sp

我正在该数据帧上调用此方法:

files['description'] = files.loc[:,'description'].apply(lambda x: textprocessing(str(x)))

您可以根据自己的方便获取任何数据。由于某些政策,我无法分享数据。

您可以尝试在一个循环中完成它,而不是在每个循环中创建 stemmer/stop_word

  STEMMER = PorterStemmer()
  STOP_WORD = stopwords.words('english')
  def textprocessing(text):

    return ''.join(STEMMER.stem(item)  for token in re.sub(r'\s*(?:([^a-zA-Z0-9._\s "])|\b(?:[a-z])\b)'," ",text.lower()).split() if token not in STOP_WORD and len(token) > 1)

你也可以使用 nltk 来删除不需要的词

from nltk.tokenize import RegexpTokenizer
STEMMER = PorterStemmer()
STOP_WORD = stopwords.words('english')
TOKENIZER = RegexpTokenizer(r'\w+')
def textprocessing(text):
    return ''.join(STEMMER.stem(item)  for token in TOKENIZER.tokenize(test.lower()) if token not in STOP_WORD and len(token) > 1)