首页 > 解决方案 > 如何优化预处理所有文本文档而不使用 for 循环在每次迭代中预处理单个文本文档?

问题描述

我想优化下面的代码,以便它可以有效地处理 3000 个文本数据,然后将这些数据馈送到 TFIDF Vectorizer 和 links() 进行聚类。

到目前为止,我已经使用 pandas 阅读了 excel 并将数据框保存到列表变量中。然后我将列表中的每个文本元素迭代为标记,然后从元素中过滤掉停用词。过滤后的元素存储到另一个变量中,并且该变量存储在列表中。所以最后,我创建了一个已处理文本元素的列表(来自列表)。

我认为可以在创建列表和过滤掉停用词时执行优化,同时将数据保存到两个不同的变量中:documents_no_stopwords 和 processes_words。

如果有人可以帮助我或建议我遵循的方向,那就太好了。

temp=0
df=pandas.read_excel('File.xlsx')

for text in df['text'].tolist():
    temp=temp+1
    preprocessing(text)
    print temp


def preprocessing(word):

    tokens = tokenizer.tokenize(word)

    processed_words = []
    for w in tokens:
        if w in stop_words:
            continue
        else:
    ## a new list is created with only the nouns in them for each text document
            processed_words.append(w)
    ## This step creates a list of text documents with only the nouns in them
    documents_no_stopwords.append(' '.join(processed_words))
    processed_words=[]

标签: pythonpandasnlpnltk

解决方案


您需要首先制作set停用词并使用列表理解来过滤标记。

def preprocessing(txt):
    tokens = word_tokenize(txt)
    # print(tokens)
    stop_words = set(stopwords.words("english"))
    tokens = [i for i in tokens if i not in stop_words]

    return " ".join(tokens)

string = "Hey this is Sam. How are you?"
print(preprocessing(string))

输出:

'Hey Sam . How ?'

而不是使用for循环,使用df.apply如下:

df['text'] = df['text'].apply(preprocessing)

为什么集合比列表更受欢迎

stopwords.words() If you check中有重复的条目,len(stopwords.words())并且len(set(stopwords.words())) 集合的长度小了几百。这就是为什么set这里首选。

list这是使用和性能之间的区别set

x = stopwords.words('english')
y = set(stopwords.words('english'))

%timeit new = [i for i in tokens if i not in x]
# 10000 loops, best of 3: 120 µs per loop

%timeit old = [j for j in tokens if j not in y]
# 1000000 loops, best of 3: 1.16 µs per loop

而且list-comprehension比正常速度更快for-loop


推荐阅读