0

I have a string contains a set of values i have extract a word(space should ignore) after a substring I tried splitting the string

text = text.split("Vehicle Number",1)[1]

text contains Vehicle Number 4092 casuality 230 \n report based on 23/54/2 accidents 0192

I have to store the values (Dictionary)

Vehicle Number : 4092,
report based on : 23/54/2,
accidents : 0192

How can i achieve this ?

1 Answer 1

1

There are many ways to do this. A clean way given a static set of words but dynamic positions:

text = "Vehicle Number 4092 casuality 230 \n report based on 23/54/2 accidents 0192"
text = text.split()

dictionary = {
    'Vehicle Number': text[text.index('Vehicle') + 2],
    'Report Based On': text[text.index('report') + 3],
    'Accidents': text[text.index('accidents') + 1]
}
Sign up to request clarification or add additional context in comments.

4 Comments

The string value can change , i tried taking the text by index , but will be a failure when string value changes ,
The string indices may change, but does the number of whitespaces change? @Naveen
The string may change to like this Vehicle Number 4092 casuality 230 \n report based on 23/54/2 accidents 0192 Incident Type N/A Start Lifetime 601.9 KM Date/Time 1/14/21Trigger Lifetime63302.7 KM Operator Number N/A
Thanks for the clarification. Though the current code would still work for this second example (since the initial whitespaces are the same), I'll edit it to be more safe under a new assumption that new positions can occur anywhere. @Naveen

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.