Python 使用以冒号结尾的正则表达式进行分组';:';
我有一个代码,用于将偏执词内部的单词分组,如果它在偏执词之前有相同的名称 例如: 产出:Python 使用以冒号结尾的正则表达式进行分组';:';,python,regex,Python,Regex,我有一个代码,用于将偏执词内部的单词分组,如果它在偏执词之前有相同的名称 例如: 产出: car __name__(skoda,audi,benz) 但是当在结尾提供了冒号:时,它不会输出 car __name__(skoda,audi): =>no output prints with : car __name__(benz): 我想问题在于我的正则表达式 我的代码: import collections class Group: def __init__(sel
car __name__(skoda,audi,benz)
但是当在结尾提供了冒号:
时,它不会输出
car __name__(skoda,audi): =>no output prints with :
car __name__(benz):
我想问题在于我的正则表达式
我的代码:
import collections
class Group:
def __init__(self):
self.members = []
self.text = []
with open('out.txt','r') as f:
groups = collections.defaultdict(Group)
group_pattern = re.compile(r'(\S+(?: __[^__]*__)?)\((.*)\)$')
current_group = None
for line in f:
line = line.strip()
m = group_pattern.match(line)
if m: # this is a group definition line
group_name, group_members = m.groups()
groups[group_name].members.extend(group_members.split(','))
current_group = group_name
for group_name, group in groups.items():
print "%s(%s)" % (group_name, ','.join(group.members))
在正则表达式中,只需在最后添加
:
,并通过在冒号旁边添加?
使其成为可选的,这样它将匹配两种类型的字符串格式
(\S+(?: __[^__]*__)?)\((.*)\):?$
问题在于正则表达式的末尾有一个$。这迫使正则表达式查找以括号结尾的模式 您可以通过删除正则表达式中的$来解决此问题(如果您认为会有其他尾随字符): 或者,您可以调整正则表达式,使其在模式中包含冒号出现0或1次的可能性:
(\S+(?: __[^__]*__)?)\((.*)\):?$
您可以在不使用正则表达式的情况下执行此操作:
f = [ 'car __name__(skoda,audi):\n', 'car __name__(benz):\n' ]
groups = {}
for line in f:
v = line.strip().split('__')
gname, gitems = v[1], v[2]
gitems = gitems.strip("():").split(",")
groups[gname] = groups.get(gname, []) + gitems
print groups
(\S+(?: __[^__]*__)?)\((.*)\):?$
f = [ 'car __name__(skoda,audi):\n', 'car __name__(benz):\n' ]
groups = {}
for line in f:
v = line.strip().split('__')
gname, gitems = v[1], v[2]
gitems = gitems.strip("():").split(",")
groups[gname] = groups.get(gname, []) + gitems
print groups