【发布时间】:2019-01-24 07:05:56
【问题描述】:
我想优化下面的代码,以便它可以有效地处理 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=[]
【问题讨论】:
-
stop_words是一组吗?如果没有,把它变成一个。除此之外,坦率地说,在我看来,在预处理下一切都很好。.append是常数时间运算,.join是 O(n)。如果您愿意,您可以在for w in tokens步骤期间创建连接输出,但这对您没有太大帮助。