2014-10-06 105 views
0

我在python中有一个问题,我有一个模式,可以在1到XXX倍的任何位置重复。蟒蛇 - 基于字符串的基于括号的分割字符串

的模式是我有格式的字符串

作者(所属)作者(所属)等等等等许多作者/隶属关系存在。

当你不知道你是否有1个作者(联盟)或100个实例时,Python中最好的方式是如何将字符串分割成这样的形式?

编辑 - 维克托·莱斯*(慕尼黑工业大学)阿尔方肯珀(慕尼黑工业大学),托马斯·诺伊曼(慕尼黑工业大学,德国)

这就是我与工作对象的样本串。我已经尝试过re.split/re.findall并且没有运气。我假设我正在做一些正则表达式的错误。

编辑2 - '\ w + {1,3}(\ w {1,10})'是我试图使用的模式。

我的逻辑是一个名字是1-3个单词,然后(。然后一个关系在1-10个单词之间,并关闭)。

+1

使用re.findall https://docs.python.org/2/library/re.html#re.findall – user3885927 2014-10-06 23:16:04

回答

1

这里是一个样本。 。看起来你是想(在之间(和文本)匹配没有内容)或以下是做到这一点假设它酷似以上单程

import re 
text = r'Viktor Leis* (Technische Universitt Mnchen) Alfons Kemper (Technische Universitt Mnchen) Thomas Neumann (Technische Universitt Mnchen, Germany)' 
pattern = '[^\(\)]* \([^\(]+\)' 
result = re.findall(pattern,s) 
print result 

输出:

['Viktor Leis* (Technische Universitt Mnchen)', ' Alfons Kemper (Technische Universitt Mnchen)', ' Thomas Neumann (Technische Universitt Mnchen, Germany)'] 

您可能需要移除领先,并使用带尾随空格。

0

这是想到

import re 
s = 'Bob (ABC) Steve (XYZ) Mike (ALPHA)' 
pattern = '\w+ \(\w+\)' 

>>> re.findall(pattern,s) 
['Bob (ABC)', 'Steve (XYZ)', 'Mike (ALPHA)'] 
+0

嘿先生! 感谢您的建议!我原先使用re的时候曾经想过同样的事情。我的表情很相似。我实际上尝试过re.split,但无济于事。我一直在与你的空集。也许如果我包含一个示例行,它会更好? Viktor Leis *(慕尼黑工业大学)Alfons Kemper(慕尼黑工业大学)Thomas Neumann(德国慕尼黑工业大学) 是我试图用这种模式分开的众多字符串之一。 – Jibril 2014-10-06 23:23:04

0

的第一件事情你可以做这样的:

thing="Author1 (Affiliation) Author2 (Affiliation) Author3 (Affiliation)" 
s=thing.split(') ') 

list=[] 
for i in s: 
    if not i.endswith(')'): 
     list.append(i+')') 
    else: 
     list.append(i) 
+0

你好!谢谢。这可能必须是我所做的 - 比试图找出我遇到的正则表达式问题好得多。 – Jibril 2014-10-06 23:39:16

+0

Simpler总是更好! (如果你这样做,一定要标记它'接受') – 2014-10-06 23:51:57