考虑这段文字:
Would you like to have responses to your questions sent to you via email ?
我将通过这样标记来为几个词提出多个选择:
Would you like [to get]|[having]|g[to have] responses to your questions sent [up to]|g[to]|[on] you via email ?
选项在括号内并由竖线
分隔 好的选择前面有一个 g
我想解析这句话以获得这样的文本格式:
Would you like __ responses to your questions sent __ you via email ?
列表如下:
[
[
{"to get":0},
{"having":0},
{"to have":1},
],
[
{"up to":0},
{"to":1},
{"on":0},
],
]
我的标记设计可以吗?
如何对句子进行正则表达式以获得所需的结果并生成列表?
编辑:需要面向用户的标记语言
请您参考如下方法:
我会添加一些分组括号 {},并且输出的不是字典列表,而是字典列表。
代码:
import re
s = 'Would you like {[to get]|[having]|g[to have]} responses to your questions sent {[up to]|g[to]|[on]} you via email ?'
def variants_to_dict(variants):
dct = {}
for is_good, s in variants:
dct[s] = 1 if is_good == 'g' else 0
return dct
def question_to_choices(s):
choices_re = re.compile(r'{[^}]+}')
variants_re = re.compile(r'''\|?(g?)
\[
([^\]]+)
\]
''', re.VERBOSE)
choices_list = []
for choices in choices_re.findall(s):
choices_list.append(variants_to_dict(variants_re.findall(choices)))
return choices_re.sub('___', s), choices_list
question, choices = question_to_choices(s)
print question
print choices
输出:
Would you like ___ responses to your questions sent ___ you via email ?
[{'to have': 1, 'to get': 0, 'having': 0}, {'to': 1, 'up to': 0, 'on': 0}]
