Understanding How to Obtain the Value in Regular Expressions from Data in a Specific Format

Asked 1 years ago, Updated 1 years ago, 390 views

We are currently creating a program that retrieves settings and settings separately from text files in the format below.

<Format>
test login_id:userid
authority:root folder:root123
login password:1234***

<Formatting >
·There is a half-width space between the setting items and the setting.
Example
Configuration Items
folder:
Configuration root123

·Setting items are written in one or more words.There is no single word or space in the setting.
Example
Settings (login password:), Settings (1234****)

·There may be more than one set per line for setting items and setting sets.However, there is no limit on the number of spaces in each set (one or two spaces).
Example
authority:root folder:root123

<What do you want to do>
·I would like to obtain each value as a dictionary type in python.
data=[{"test login_id":userid}, {"authority":"root"}, {"folder":"root123"}, {"login password":"1234***"}]

I'm sorry to ask you a question when you haven't written the code yet, but I can't think of anything at this point in my ability, so I asked you a question first.
If you have any ideas, please let me know.
I look forward to your kind cooperation.

python regular-expression

2023-01-22 12:06

1 Answers

import re

text = ''
test login_id —userid
authority:root folder:root123
login password: 1234***
'' .lstrip()

data=[{k:v}fork, vin re.findall(r'\s*(.+?):\s+([^\s]]+)', text)]
print(data)

# [{'test login_id':'userid'}, {'authority':'root'}, {'folder':'root123'}, {'login password':'1234**'}]


2023-01-22 12:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.