Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于数据帧的python快速文本处理_Python_Regex_Pandas_Nltk_Python Textprocessing - Fatal编程技术网

基于数据帧的python快速文本处理

基于数据帧的python快速文本处理,python,regex,pandas,nltk,python-textprocessing,Python,Regex,Pandas,Nltk,Python Textprocessing,我正在用python编写一个电子商务数据包。我已经用python加载了这些数据,并将其转换为一个数据帧。现在,我想对这些数据执行文本处理,比如删除不需要的字符、停止字、词干等。目前,我应用的代码工作正常,但这需要很多时间。我有大约200万行数据要处理,而且要花很长时间来处理。我在10000行上尝试了这个代码,大约花了240秒。我第一次从事这种项目。任何有助于缩短时间的措施都会非常有帮助 提前谢谢 from nltk.stem import PorterStemmer from nltk.corp

我正在用python编写一个电子商务数据包。我已经用python加载了这些数据,并将其转换为一个数据帧。现在,我想对这些数据执行文本处理,比如删除不需要的字符、停止字、词干等。目前,我应用的代码工作正常,但这需要很多时间。我有大约200万行数据要处理,而且要花很长时间来处理。我在10000行上尝试了这个代码,大约花了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 = 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来删除unwant单词

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)

一个可能有用的快速更改:看起来stopwords通常是一个列表,其中包含2400个条目。如果不是在stopwords中的w,那么将其设置为一组应该会大大加快
。先在较小的摘录上尝试您的更改。此外,apply有时似乎比正常的列表理解慢-可能值得提取列,将代码(实际上是一个很好的处理)作为列表理解,然后重新插入…我以前在pandas上体验过,
apply
比在列表或字典等其他结构中应用函数要慢得多。是否有特定的原因需要它们出现在
pandas.DataFrame
中?你们考虑过使用另一个吗?我正在通过数据库加载它。这就是为什么我要将其转换为数据帧来处理它。是否有任何其他数据存储选项,我可以申请和工作很容易?谢谢。。!!!在代码中几乎没有修复的情况下,它确实将速度提高了几倍。