2015-09-02 55 views
0

例如,基於Python中的邏輯關係做這個字符串patten替換的最快方法是什麼?

1. str1 = 'A>1 and A>=3 and B<2 and B<=3 and B<1 ...', should be substituted to: 
    str1 = 'A>=3 and B<1 ...'; 

2. str2=['A=1 and B<=2 ...', 'A=1 and B>2 ...'], should be substituted to: 
    str2=['A=1 ...'], where B is skipped 

A,B可以是任何長度的法律蟒標識符。在str1和str2中都有未知數量的邏輯操作數。

通常的正則表達式搜索的方式是相當具有挑戰性的解決這個問題。任何黑客的想法?

編輯:

爲了使問題簡單化,我們考慮 '和' 只操作,所有操作數的排序爲一個字符串,即

'A<x and A<y and A<z' will always appear next to each other 
+0

我實在不明白你怎麼可以用正則表達式解決這個問題。我想說你需要解析你的字符串(如果你的格式被充分限制,這一步可以用正則表達式來完成),並對結果運行一個簡單的解釋器。 – fjarri

回答

1
from itertools import groupby 
import re 


str1 = "A>1 and A>3 and B<2 and B<3" 
comparisions = [s.strip() for s in str1.split("and")] 
operands = [re.search(r'(\w+)([<>][=]?)(\w+)',c).groups() for c in comparisions]# 

tot={}#total results 
for k,g in groupby(operands,lambda x:x[0]):#group by variable1 
    for arg in g:#arg is the match with list [var1,compareitem,var2] 
     if k not in tot:tot[k] = {} 
     if arg[1] in tot[k]: 
      print("do the overwrite handling!") 
     tot[k][arg[1]] = arg[2] 

#sort tot 
sortedkeys = sorted(tot, key=lambda x: x[0]) 

resub_str = " and ".join([comp+"".join([k+tot[comp][k] for k in tot[comp]]) for comp in sortedkeys]) 
print(resub_str) 

輸出:

do the overwrite handling! 
do the overwrite handling! 
A>3 and B<3 

理念:

  1. 拆分在條件語句中的陣列的字符串。 所以,我們有[A>1,A>3,B<2,B<3]等。
  2. 搜索帶有圖案的每個條件,符合[VARIABLE1] [COMPARE_ITEM] [變量2]其中COMPARE_ITEM<,>,<=,>=
  3. 我們現在GROUP BY VARIABLE1一個搜索結果,如果我們已經有一個條件VARIABLE1。如果我們有 - 做覆蓋。如果沒有,只需插入它。
  4. 排序數組由VARIABLE1" and "

加盟條件部分完全可以提高通過不只是搜索VAR1,同時也尋找變量2的代碼,併爲所使用的每個變量的引用。

(使像A<B and A< 4條件導致相同B>A and 4>A)。

+0

超酷!對問題的第二部分有任何破解? – Rex

+0

自己動手,不應該那麼辛苦。如果你願意,我會解釋我的想法是什麼。你可以將這個想法應用到第二部分 – user2358582

+0

你能解釋你的想法嗎? – Rex

相關問題