python字符串创建_在Python上创建完整的字符串
我需要在葡萄牙語字符串上執行詞干.為此,我使用nltk.word_tokenize()函數對字符串進行標記,然后單獨生成每個單詞.之后,我重建了字符串.它工作正常,但表現不佳.我怎樣才能讓它更快?字符串長度約為200萬字.
tokenAux=""
tokens = nltk.word_tokenize(portugueseString)
for token in tokens:
tokenAux = token
tokenAux = stemmer.stem(token)
textAux = textAux + " "+ tokenAux
print(textAux)
抱歉英文不好,謝謝!
解決方法:
string是不可變的,因此,如果字符串很長,每次更新字符串都不是好習慣. link here解釋了連接字符串和顯示性能分析的各種方法.而且,因為迭代只進行一次,所以最好選擇生成器表達而不是列表理解.有關詳細信息,您可以查看discussion here.在這種情況下,使用帶有join的生成器表達式可能會有所幫助:
使用my_text作為長字符串:len(my_text) – > 444399
使用timeit進行比較:
%%timeit
tokenAux=""
textAux=""
tokens = nltk.word_tokenize(my_text)
for token in tokens:
tokenAux = token
tokenAux = stemmer.stem(token)
textAux = textAux + " "+ tokenAux
結果:
1 loop, best of 3: 6.23 s per loop
使用帶有join的generator表達式:
%%timeit
' '.join(stemmer.stem(token) for token in nltk.word_tokenize(my_text))
結果:
1 loop, best of 3: 2.93 s per loop
標簽:python,nlp,nltk,stemming
來源: https://codeday.me/bug/20190622/1264573.html
總結
以上是生活随笔為你收集整理的python字符串创建_在Python上创建完整的字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 导出jar插件_Fluttify输出的F
- 下一篇: python process 函数_Py