2017-06-08 18 views
0

我正在使用包的findall()函數進行簡單的正則表達式字符串搜索。 在執行負面情景的單元測試時,我發現一些特殊字符返回錯誤代碼,它們在#符號後面的註釋中給出。 我的問題是爲什麼這些字符返回錯誤代碼,我怎樣才能用搜索字符串替換它們與轉義序列? 請告訴我的代碼替換轉義序列:Python:正則表達式搜索在搜索多個字符時出現錯誤的特殊字符

import re 
search="database" 
search="c++" # error: multiple repeat 
search="c\+\+" #working 
search="c+" #working 
search="c#" #working 
search="j!!" #working 
search="x$$" #working 
search="++j" #error: nothing to repeat 
search="~~c" #working 
search="[email protected]@" #working 
search="j##" #working 
search="c%%" #working 
search="j&&" #working 
search="j**" #error: multiple repeat 
search="j*" #* is wild card 
search="c(github)" #working 
search="c--" #working 
search="c==" #working 
document="i did c++ programming. I am a c++ programming enthusiast. I love 
working on c++ algirithms. I have experience in 3.5 years of c++ programming 
skills " 
n=len(re.findall(search,document)) 
print("Keyword Frequency: ",search ," Count: ",n) 

碼打印的最後一條語句的輸出()是針對爲了便於理解,每個搜索詞給出。 我需要的解決方案必須具備以下能力:

  1. 識別特殊字符序列。 (例如,它可能是:++或+++或+++++或「++ j」或「j **」等

  2. 在識別出特殊字符序列後,解決方案代碼應該替換特殊字符與 「++」 或 「+++」 或 「+++++」 或 「+ J」 或 「**Ĵ」

  3. 創建新的搜索字符串

謝謝爲您的解決方案提前

回答

1

正則表達式模塊帶有一個功能:re.escape()。所以:

import re 

search = "c++" 
# ... 
document = """i did c++ programming. I am a c++ programming enthusiast. I love 
working on c++ algirithms. I have experience in 3.5 years of c++ programming 
skills """ 
n = len(re.findall(re.escape(search), document)) 
print("Keyword Frequency: ", search, " Count: ", n) 

應該做的就好了......現在,你爲什麼要使用正則表達式,而不是str.count()這樣一個簡單的任務,你需要回答自己的問題。

相關問題