使用python提取括号中的部分字符串

使用python提取括号中的部分字符串,python,csv,substring,Python,Csv,Substring,我有一个带有字符串的列的csv文件。字符串的一部分在括号中。我希望将括号中的字符串部分移到另一列,并保留字符串的其余部分 例如:我希望转换: LC(Carbamidomethyl)RLK 到 正则表达式解 如果字符串中只有一个括号组,则可以使用以下正则表达式: >>> a = "LC(Carbamidomethyl)RLK" >>> re.sub('(.*)\((.+)\)(.*)', '\g<1>\g<3> \g<2

我有一个带有字符串的列的csv文件。字符串的一部分在括号中。我希望将括号中的字符串部分移到另一列,并保留字符串的其余部分

例如:我希望转换:

LC(Carbamidomethyl)RLK     

正则表达式解 如果字符串中只有一个括号组,则可以使用以下正则表达式:

>>> 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
过程是获取括号的位置(如果有)并在需要的地方剪切字符串。然后,我们连接结果

每种方法的性能 很明显,字符串操作是最快的方法:

>>> 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

你的字符串中有很多括号吗?如L(abc)C(def)FIV到LCFIV abcdefNo。括号中只有这一个值。非常感谢!我来试试这个。我需要将此应用于一个大型csv文件。我是编程新手,我需要为我的研究处理大型数据集。请注意,由于使用正则表达式,此解决方案可能会非常缓慢。。。我已经用一个字符串操作解决方案更新了我的答案,速度快了10倍;)如何处理字符串中有多组括号的情况?例如:DRC(氨基甲基)KPVNTFVHESLADVQAVC(氨基甲基)SQKNVACK非常感谢Maxime!
(.*)       #! 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'