用于python中文本清理/处理的管道

问题描述 投票:4回答:2

我是python环境(jupyter notebook)的新手,我正在尝试处理相对庞大的文本数据。我想通过应用以下步骤并按相同顺序处理它:

剥离空格,小写,词干,删除标点但保留字内破折号或连字符,删除停用词,删除符号,删除空格,

我希望我可以获得一个可以执行任务的单个函数,而不是单独执行它们,是否有任何单个库和/或函数可以帮助?如果没有,那么定义一个函数来执行它们的最简单方法是一次运行?

python-3.x nlp nltk jupyter-notebook text-processing
2个回答
3
投票

正如评论中所提到的,它可以使用Python中多个库的组合来完成。一个可以执行它的功能可能如下所示:

import nltk
import re
import string
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer # or LancasterStemmer, RegexpStemmer, SnowballStemmer

default_stemmer = PorterStemmer()
default_stopwords = stopwords.words('english') # or any other list of your choice
def clean_text(text, ):

    def tokenize_text(text):
        return [w for s in sent_tokenize(text) for w in word_tokenize(s)]

    def remove_special_characters(text, characters=string.punctuation.replace('-', '')):
        tokens = tokenize_text(text)
        pattern = re.compile('[{}]'.format(re.escape(characters)))
        return ' '.join(filter(None, [pattern.sub('', t) for t in tokens]))

    def stem_text(text, stemmer=default_stemmer):
        tokens = tokenize_text(text)
        return ' '.join([stemmer.stem(t) for t in tokens])

    def remove_stopwords(text, stop_words=default_stopwords):
        tokens = [w for w in tokenize_text(text) if w not in stop_words]
        return ' '.join(tokens)

    text = text.strip(' ') # strip whitespaces
    text = text.lower() # lowercase
    text = stem_text(text) # stemming
    text = remove_special_characters(text) # remove punctuation and symbols
    text = remove_stopwords(text) # remove stopwords
    #text.strip(' ') # strip whitespaces again?

    return text

使用(Python2.7测试它,但也应该在Python3中工作):

text = '  Test text !@$%$(%)^   just words and word-word'
clean_text(text)

结果是:

u'test text word word-word'

0
投票

或者,您也可以使用我的管道创建器类来处理我最近完成的文本数据。在github中找到heredemo_pipe.py几乎涵盖了你想做的事情。

© www.soinside.com 2019 - 2024. All rights reserved.