如何在 NLP 问题中加快我的代码清理文档



我写了一个小函数来清理文本文档。该函数将删除任何长度小于 2 的单词,它将删除所有特殊字符和所有完全由数字组成的单词,并使用自定义列表停止单词。它还将进行简单的拼写检查并删除所有"假词"。但是,该功能运行速度超慢,我想有什么方法可以加快速度。

def clean_up_phrases_no_stopwords_no_short_letters_no_numeric(kx):
kx=" ".join([x for x in kx.split(" ") if len(x)>2])
kx=" ".join([x for x in kx.split(" ") if x not in total_stopword])    
kx=" ".join(re.sub('[^A-Za-z0-9]+', '', x) for x in kx.split(" "))    
kx=" ".join([x for x in kx.split(" ") if not x.isdigit()])
filted_fake_words=list(filter(None, [return_valid_word(x) for x in kx.split(" ") ]))    
kx=" ".join(filted_fake_words)        
return kx
def return_valid_word(word):
word_token=word.split(" ")
word_token=list(filter(None, word_token))
word_list=list()
for x in word_token:
word_list.append(lemma_single_word(x))
if len([x for x in word_list if x in word_set])>0:
return word
else:
filtered_word=[return_valid_single_nondict_word(x) for x in word_list]
if filtered_word==[None]:
return None
else:
word=" ".join([return_valid_single_nondict_word(x) for x in word_list])
return word
def return_valid_single_nondict_word(word):
character=list(word)
max_character_num=Counter(character).most_common(1)[0][1]
if max_character_num > 3:
return None
else:
return word
'''

尝试使用 nltk。它将简化过程。

示例代码:

from nltk.corpus import stopwords 
from nltk.tokenize import word_tokenize 
data = "... your text here ..."
stop_words = set(stopwords.words("english"))
tokens = word_tokenize(data)
resultset = [w for w in tokens if not w in stop_words] 

添加额外的过滤条件以移除您要丢弃的其他字词。

代码中最重要的时间是数据复制x for x in kx.split(" ")只是生成器,但是您每次都强制复制数据,kx=" ".join(word_token=list(list(filter(。因此,您应该以最小化数据复制的方式编写代码。

在这种特殊情况下,您可以使用一次x for x in kx.split(" "),如下所示:

def clean_up_phrases_no_stopwords_no_short_letters_no_numeric(phrase):
filtered_words=[]
for word in phrase.split(" "):
if not len(word)>2: continue # continue, so just skip this word
if word in total_stopword: continue
word = re.sub('[^A-Za-z0-9]+', '', word) # modification of word
if word.isdigit(): continue
if not is_lemma_single_word(word): continue
if not is_valid_single_nondict_word(word): continue
filtered_words.append(word)
return " ".join(filtered_x)

在这种情况下,您应该重写单词测试函数以返回 True 或 False,而不是 word 或 None。

这里还有一些地方需要进一步优化,例如,不是收集filtered_word而是收集生成的字符串等。

最新更新