2014-01-28 33 views
3

我有一個帶有字符串的列的csv文件。部分字符串在括號中。我希望將括號中的字符串部分移到不同的列,並保留字符串的其餘部分。使用python在括號中提取部分字符串

例如:我想轉換:

LC(Carbamidomethyl)RLK  

LCRLK Carbamidomethyl 
+0

你將有很多括號在你的字符串?像L(abc)C(def)FIV到LCFIV abcdef –

+0

不可以。它只在圓括號中有這個值。 – kkhatri99

回答

2

正則表達式的解決方案

如果你只有一個括號組中的字符串,就可以使用這個表達式:

>>> a = "LC(Carbamidomethyl)RLK" 
>>> re.sub('(.*)\((.+)\)(.*)', '\g<1>\g<3> \g<2>', a) 
'LCRLK Carbamidomethyl' 
>>> a = "LCRLK" 
>>> re.sub('(.*)\((.+)\)(.*)', '\g<1>\g<3> \g<2>', a) 
'LCRLK' # works with no parentheses too 

正則表達式分解:

(.*)  #! Capture begin of the string 
\(  # match first parenthesis 
    (.+)  #! Capture content into parentheses 
\)   # match the second 
(.*)  #! Capture everything after 

--------------- 
\g<1>\g<3> \g<2> # Write each capture in the correct order 

字符串處理的解決方案

更快的解決方案,對龐大的數據集是:

begin, end = a.find('('), a.find(')') 
if begin != -1 and end != -1: 
    a = a[:begin] + a[end+1:] + " " + a[begin+1:end] 

的過程是讓括號的位置(如果有任何)和把弦放在我們想要的地方。然後,我們連接結果。

性能每種方法的

很明顯,該字符串操作是最快的方法:

>>> timeit.timeit("re.sub('(.*)\((.+)\)(.*)', '\g<1>\g<3> \g<2>', a)", setup="a = 'LC(Carbadidomethyl)RLK'; import re") 
15.214869976043701 


>>> timeit.timeit("begin, end = a.find('('), a.find(')') ; b = a[:begin] + a[end+1:] + ' ' + a[begin+1:end]", setup="a = 'LC(Carbamidomethyl)RL'") 
1.44008207321167 

多括號設置

看評論

>>> a = "DRC(Carbamidomethyl)KPVNTFVHESLADVQAVC(Carbamidomethyl)SQKNVACK" 
>>> while True: 
...  begin, end = a.find('('), a.find(')') 
...  if begin != -1 and end != -1: 
...   a = a[:begin] + a[end+1:] + " " + a[begin+1:end] 
...  else: 
...   break 
... 
>>> a 
'DRCKPVNTFVHESLADVQAVCSQKNVACK Carbamidomethyl Carbamidomethyl' 
+0

非常感謝!我會試試這個。我需要將它應用於一個大型的csv文件。我是編程新手,需要爲我的研究處理大型數據集。 – kkhatri99

+0

請注意,由於正則表達式的使用,此解決方案可能會非常緩慢......我使用字符串操作解決方案更新了我的答案,速度提高了10倍;) –

+0

太棒了!謝謝!! – kkhatri99

相關問題