我有一个带有字符串的列的csv文件。部分字符串在括号中。我希望将括号中的字符串部分移到不同的列,并保留字符串的其余部分。使用python在括号中提取部分字符串
例如:我想转换:
LC(Carbamidomethyl)RLK
到
LCRLK Carbamidomethyl
我有一个带有字符串的列的csv文件。部分字符串在括号中。我希望将括号中的字符串部分移到不同的列,并保留字符串的其余部分。使用python在括号中提取部分字符串
例如:我想转换:
LC(Carbamidomethyl)RLK
到
LCRLK Carbamidomethyl
如果你只有一个括号组中的字符串,就可以使用这个表达式:
>>> 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'
你将有很多括号在你的字符串?像L(abc)C(def)FIV到LCFIV abcdef –
不可以。它只在圆括号中有这个值。 – kkhatri99