简体   繁体   中英

How to split a string based on certain regex? (In python)

I have a string that is a bunch of sentences that are split up by things like "title": , "date": , etc.

I want to split up this string based on those delimiters. Right now I have this ..

line =  re.split(r'("[a-z]: ")', line)



  {"date": "Jul 18, 2017, 4:10 AM", 
    "text": "Best / cheapest", 
    "state_or_country_or_utility": "Norway Travel Forum", 
    "responses": ["The local train www.nsb.no"],
    "title": "airport transfer "}

You can use ast.literal_eval :

import ast
s = '{"date": "Jul 18, 2017, 4:10 AM", "text": "Best / cheapest", "state_or_country_or_utility": "Norway Travel Forum", "responses": ["The local train www.nsb.no"], "title": "airport transfer "}'
final_data = ast.literal_eval(s)

Output:

{'date': 'Jul 18, 2017, 4:10 AM', 'text': 'Best / cheapest', 'state_or_country_or_utility': 'Norway Travel Forum', 'responses': ['The local train www.nsb.no'], 'title': 'airport transfer '}

Your input is JSON, you can use json.loads() .

import json

data = '''{"date": "Jul 18, 2017, 4:10 AM", 
    "text": "Best / cheapest", 
    "state_or_country_or_utility": "Norway Travel Forum", 
    "responses": ["The local train www.nsb.no"],
    "title": "airport transfer "}'''

result = json.loads(data)
print('Title = ', result['title'])
print('Date = ', result['date'])

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM