[英]Matching multiple patterns in a string
我有一个看起来像这样的字符串:
s = "[A] text [B] more text [C] something ... [A] hello"
基本上它由[X] chars
,我试图在每个[X]
之后获取文本。
我想产生这个字典(我不在乎顺序):
mydict = {"A":"text, hello", "B":"more text", "C":"something"}
我正在考虑使用正则表达式,但我不确定这是否是正确的选择,因为在我的情况下,[A]、[B] 和 [C] 的顺序可以改变,所以这个字符串也有效:
s = "[A] hello, [C] text [A] more text [B] something"
我不知道如何正确提取字符串。 任何人都可以指出我正确的方向吗? 谢谢。
不确定这是否正是您要查找的内容,但由于重复而失败
s = "[A] hello, [C] text [A] more text [B] something"
results = [text.strip() for text in re.split('\[.\]', s) if text]
letters = re.findall('\[(.)\]', s)
dict(zip(letters, results))
{'A': 'more text', 'B': 'something', 'C': 'text'}
由于输出如下所示:
In [49]: results
Out[49]: ['hello,', 'text', 'more text', 'something']
In [50]: letters
Out[50]: ['A', 'C', 'A', 'B']
要解决重复问题,您可以执行以下操作....
mappings = {}
for pos, letter in enumerate(letters):
try:
mappings[letter] += ' ' + results[pos]
except KeyError:
mappings[letter] = results[pos]
这给出: {'A': 'hello, more text', 'B': 'something', 'C': 'text'}
更新
或者更好的是,您可以考虑使用默认字典:如下所示:在此处输入链接描述
预期输出:
mydict = {"A":"text, hello", "B":"more text", "C":"something"}
import re
s = "[A] text [B] more text [C] something ... [A] hello"
pattern = r'\[([A-Z])\]([ a-z]+)'
items = re.findall(pattern, s)
output_dict = {}
for x in items:
if x[0] in output_dict:
output_dict[x[0]] = output_dict[x[0]] + ', ' + x[1].strip()
else:
output_dict[x[0]] = x[1].strip()
print(output_dict)
>>> {'A': 'text, hello', 'B': 'more text', 'C': 'something'}
这是一个简单的解决方案:
#!/usr/bin/python
import re
s = "[A] text [B] more text [C] something ... [A] hello"
d = dict()
for x in re.findall(r"\[[^\]+]\][^\[]*",s):
m = re.match(r"\[([^\]*])\](.*)",x)
if not d.get(m.group(1),0):
#Key doesn't already exist
d[m.group(1)] = m.group(2)
else:
d[m.group(1)] = "%s, %s" % (d[m.group(1)], m.group(2))
print d
印刷:
{'A': ' text , hello', 'C': ' something ... ', 'B': ' more text '}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.