【发布时间】:2020-08-30 09:05:17
【问题描述】:
我正在使用 Python 并使用正则表达式模块。不过,很高兴为以下内容使用替代解析方法。事实上,我尽量避免使用正则表达式。
我对解决问题所需的 python 感到满意。我只是在使用正则表达式模式。
一些示例数据(每行单独提供):
This is a key : this_is_an_id_related_to_this_value Sometimes just the ID present but in some cases a basic sentence delimited by more than one space Second key : id2 description where I assume only one space is allowed, no other assumptions on what the content might contain <relates_to_id>
Container : 123ABC <view5>
Container : A1B2 Some Sample Data Located at Rack 6 Storage Place : 1234 Think about another random description <view3>
Container : AbACc123 Some more sample data with some description Storage Place : B14hb14h Blah Blah Blah <view5>
Container : C0Nt41n3r8 Cleanup on isle 9 Storage Place : DEDE123 Storage Fridge 2 <view8>
Container : Eb0l4 Infectious disease test rack 2 Storage Place : G3nX XOXO Special Fridge 4 Col : 8 Row : 3 <view8>
这应该翻译成:
[
{
"This is a key": {
"id": "this_is_an_id_related_to_this_value",
"description": "Sometimes just the ID present but in some cases a basic sentence delimited by more than one space"
},
"Second key": {
"id": "id2",
"description": "description where I assume only one space is allowed, no other assumptions on what the content might contain"
},
"relates_to": "relates_to_id"
},
{
"Container": {
"id": "123ABC"
},
"relates_to": "view5"
},
{
"Container": {
"id": "A1B2",
"description": "Some Sample Data Located at Rack 6"
},
"Storage Place": {
"id": "1234",
"description": "Think about another random description"
},
"relates_to": "view3"
},
{
"Container": {
"id": "AbACc123",
"description": "Some more sample data with some description"
},
"Storage Place": {
"id": "B14hb14h",
"description": "Blah Blah Blah"
},
"relates_to": "view5"
},
{
"Container": {
"id": "C0Nt41n3r8",
"description": "Cleanup on isle 9"
},
"Storage Place": {
"id": "DEDE123",
"description": "Storage Fridge 2"
},
"relates_to": "view8"
},
{
"Container": {
"id": "Eb0l4",
"description": "Infectious disease test rack 2"
},
"Storage Place": {
"id": "G3nX",
"description": "XOXO Special Fridge 4"
},
"Col": 8,
"Row": 3,
"relates_to": "view8"
},
]
在这个阶段,我对只处理父键、值的解决方案感到满意,例如
[
{
"This is a key": "this_is_an_id_related_to_this_value Sometimes just the ID present but in some cases a basic sentence delimited by more than one space",
"Second key": "id2 description where I assume only one space is allowed, no other assumptions on what the content might contain",
"relates_to": "relates_to_id"
},
# ...
]
我相信我可以弄清楚其余的,当我这样做时,我会提供它作为替代答案。
这是我尝试使用正则表达式的方法,see demo
(?<key>((?! +)[A-Za-z]*\s?)*):(?<value>.*)
我认为将上述内容包含在 ()* 中会成为 key : value 重复的关键。但它失败了,see demo
这几乎得到了我想要的,但我没有重复 key : value 重复,see demo
【问题讨论】: