I want to extract characters from the message and save them in json.

Asked 2 years ago, Updated 2 years ago, 16 views

msg="Dictionary registration: Doraemon_Crayon Shin-chan"

Now,

{
  "Doraemon": "Shin-chan Crayon".
}

In other words, I would like to remove "Dictionary Registration" from the body of the message and save only "Doraemon" and "Crayon Shin-chan" in json. What should I do?

python

2022-09-30 11:23

2 Answers

I think it's easy to replace with regular expressions.
^Dictionary registration:{\n"$1":"$2"\n}
I think you can replace it with .

Specifically, you can use re in the standard library that handles regular expressions, for example:

import re
msg="Dictionary registration: Doraemon_Crayon Shin-chan"
pat=re.compile(r'^Dictionary registration: (.+)_(.+)$')
print(pat.sub('{\n"\\1":"\\2"\n}',msg))
# {
# "Doraemon": "Shin-chan Crayon".
# }


2022-09-30 11:23

Dictionary registration: If is a fixed string, you can do the following:

import json

data = {}
key,value=msg[5:].split('_')
data [key] = value
s=json.dumps(data)
print(s)


2022-09-30 11:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.