python - 如何优化预处理所有文本文档而不使用 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=[]
解决方案
您需要首先制作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
。
推荐阅读
- google-chrome-extension - 从 chrome 扩展打开 chrome:// UI 页面时不允许加载本地资源
- swift - 我想让 UIBarButtonItem 与 setEditing 一起使用
- javascript - 我需要让这个 JavaScript 函数只输出整数
- javascript - React 中的 Javascript 内联样式 - null、未定义、空对象、继承还是无?
- java - java.lang.UnsatisfiedLinkError:dlopen 失败:找不到库“libagora-rtc-sdk.so”
- amazon-web-services - 在 terraform 中分离 Elastic IP
- android - Android TWRP 不使用 ADB 闪烁;失败(远程:'未知命令')
- python-3.x - 另一个“fk_name '' is not a foreignkey to”问题 [Python/Django]
- visual-studio-2019 - 设备驱动程序不会安装在任何设备上,如果需要,请使用原始驱动程序。[安全证书]
- python - 如何使用多处理来并行化收集与给定条件匹配的项目的过滤功能?