Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to extract contents depending upon its title using python

I need to extract text depending on the title, let's say in the below code, I need to display Experience field. Like, let's assume I have a text file as ab.text which has data like:

Name: xyz
Experience: 
123 company 2016-2017
567 company 2017-2018
yzx company 2018-2019

Skills:
Python, MachineLearning, Java.

Now i need to read this text file and display only the texts that is under experience field. Note: The order of Name , expereince and skills may vary. I am new to python please help me on this.

Expected Output:

Experience: 
123 company 2016-2017
567 company 2017-2018
yzx company 2018-2019
like image 414
Sampath Shanbhag Avatar asked Sep 18 '26 00:09

Sampath Shanbhag


1 Answers

You could use re module and parse the text with it:

data = '''Name: xyz
Experience:
123 company 2016-2017
567 company 2017-2018
yzx company 2018-2019

Skills:
Python, MachineLearning, Java.'''

import re

#Step 1. Split the string
s = [g.strip() for g in re.split('^(\w+):', data, flags=re.M) if g.strip()]
# s = ['Name', 'xyz', 'Experience', '123 company 2016-2017\n567 company 2017-2018\nyzx company 2018-2019', 'Skills', 'Python, MachineLearning, Java.']

#Step 2. Convert the splitted string to dictionary
d = dict(zip(s[::2], s[1::2]))
# d = {'Name': 'xyz', 'Experience': '123 company 2016-2017\n567 company 2017-2018\nyzx company 2018-2019', 'Skills': 'Python, MachineLearning, Java.'}

print(d['Experience'])

Prints:

123 company 2016-2017
567 company 2017-2018
yzx company 2018-2019
like image 163
Andrej Kesely Avatar answered Sep 20 '26 14:09

Andrej Kesely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!