Reputation: 37
I am trying to extract data from a PDF file so I read each line of the converted text file into a list. I have a predefined list which will be used as keys. I want to create a dictionary with keys from the predefined list and extract the corresponding value. for example, the file would contain
Name : Luke Cameron
Age and Sex : 37/Male
Haemoglobin 13.0 g/dL
I have got predefined list like
keys = ['Name', 'Age', 'Sex']
My code is
for text in lines:
rx_dict = {elem:re.search(str(elem)+r':\s+\w+.\s\w+',text) for elem in keys}
The output:
{'Patient Name': None,
'Age': None,
'Sex': None
}
Desired output:
{'Patient Name': Luke Cameron,
'Age': 37,
'Sex': Male
}
NOTE: This isn't real data and resemblance is just coincidence
Upvotes: 1
Views: 135
Reputation: 103814
Here is a non-regex approach:
txt = """\
Name : Luke Cameron
Age and Sex : 37/Male
Haemoglobin 13.0 g/dL"""
keys=('Patient Name','Age','Sex')
ans={}
for t in (line.partition(':') for line in txt.splitlines() if line.partition(':')[2]):
if sum(n in t[0] for n in keys)>1:
ans.update(
{k.strip():v.strip() for k,v in zip(t[0].split(' and '), t[2].split('/'))})
else:
ans[t[0].strip()]=t[2].strip()
>>> ans
{'Name': 'Luke Cameron', 'Age': '37', 'Sex': 'Male'}
Upvotes: 0
Reputation: 43169
You could use
import re
data = """
Name : Luke Cameron
Age and Sex : 37/Male
Haemoglobin 13.0 g/dL"""
rx = re.compile(r'^(?P<key>[^:\n]+):(?P<value>.+)', re.M)
result = {}
for match in rx.finditer(data):
key = match.group('key').rstrip()
value = match.group('value').strip()
try:
key1, key2 = key.split(" and ")
value1, value2 = value.split("/")
result.update({key1: value1, key2: value2})
except ValueError:
result.update({key: value})
print(result)
Which yields
{'Name': 'Luke Cameron', 'Age': '37', 'Sex': 'Male'}
Upvotes: 1
Reputation: 703
strings_from_pdf = ["Name : Luke Cameron", "Age and Sex : 37/Male", "Haemoglobin 13.0 g/dL"]
keys = ['Name', 'Age', 'Sex']
def findKeys(keys):
dict = {}
for i in range(len(strings_from_pdf)):
if keys[0] in strings_from_pdf[i]:
_, name = strings_from_pdf[i].split(":")
dict['Patient Name: '] = name
if keys[1] in strings_from_pdf[i]:
_, age_and_gender = strings_from_pdf[i].split(":")
age, gender = age_and_gender.split("/")
dict['Age: '] = age
dict['Gender: '] = gender
return dict
dict = findKeys(keys)
Upvotes: 0