2014-01-28 31 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

相关问题