我是python环境(jupyter notebook)的新手,我正在尝试处理相对庞大的文本数据。我想通过应用以下步骤并按相同顺序处理它:
剥离空白, 小写, 词干, 删除标点符号但保留字内短划线或连字符, 删除停用词, 删除符号, 剥离空白
我希望我可以获得一个可以执行任务的单个函数,而不是单独执行它们,是否有任何单个库和/或函数可以提供帮助?如果没有,那么定义一个函数来执行它们的最简单方法就是一次运行?
答案 0 :(得分:3)
如评论中所述,可以使用Python中多个库的组合来完成。一个可以执行所有操作的功能可能如下所示:
<div *ngFor="let person of persons">
<p>{{person.name}}</p>
<p>Total <span>{{getTotal(person)}}</span></p> <!-- take a look how
I send the current person in the *ngFor loop -->
</div>
使用(Python2.7测试它,但也应该在Python3中工作):
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
结果:
text = ' Test text !@$%$(%)^ just words and word-word'
clean_text(text)
答案 1 :(得分:0)
或者,您也可以将管道创建器类用于最近完成的文本数据。在github中找到here。 demo_pipe.py
涵盖了您要做的大部分事情。