2013-11-25 41 views
0

我有一個從互聯網上獲取信息的腳本。簡而言之,我最終得到一個包含字符串的變量。基於此字符串我已設定的腳本來決定是否該字符串屬於丟棄或進一步處理信息的基礎上,如果:(Python)篩選字符串中特定術語的最佳方法?

  • 有內一個特定的詞
  • 或兩句話中以特定的順序字符串。

我想知道什麼是最好的算法是實現這個效率,並具有良好的,如果不是100%正確的準確性。

目前,我有以下代碼(大規模減少到包括特定部分,通常有循環解決這個問題,等,等):

#!/usr/bin/env python 
import re 
def findWord(z): 
    return re.compile(r'\b({0})\b'.format(z), flags=re.IGNORECASE).search 

filterList = [ 
       "term-1","term-2","term-n" 
      ] 
uncleanString = "This! is* a test [string],.}".lower() 

#Remove all punctuation 
for c in "[email protected]#%&*()[]{}/?<>,.'": 
    cleanString = uncleanString.replace(c, "") 

#Check if the words in filterList are present, if not then process further 
no = 0 
for word in filterList: 
    result = findWord(filterList[filterList.index(word)])(cleanString) 
    if result == None: 
     pass 
    else: 
     no = 1 
     break 

    if no == 0: 
     #then do further processing here, e.g. 
     print(cleanString) 
     #reset condition (when implementing code in loop(s) 
     no = 0 

在我的實際腳本我filterList大。這是一個慢腳本,需要大約30分鐘才能完成,但我認爲這更多是由於我運行它的平臺(RPi而不是PyPy),與互聯網的通信(BS4/HTTPlib)以及與MySQL數據庫...你有什麼想法可以加快這部分的速度,然後再進入細化其他部分,或者你會說上面的內容足夠嗎?

回答

-1

你可以使其更具可讀性,肯定:

if not any(word in cleanString for word in filterList): 
    # further processing 

這削減了字符串格式化和正則表達式編譯一步。

0

使交替出現一個大的正則表達式。

reg=re.compile(r'\b('+"|".join(filterList)+r')\b') 

貌似這個

\b(term-1|term-2|term-n)\b 

您不必遍歷所有的長期項目,他們都在一個正則表達式

呼叫一次編譯對象上,而不是findWord的」 「致電

reg.search 
相關問題