I have a word document that contains alphabetical bullet points along with the key: value that I am trying to input into a dictionary using docx.
Example:
This is my document
a. First name: Jeff
b. Last name: Smith
c. Position: Manager
d. Birthdate: 01/01/1990
e. Address: 123 Main Street, Smithville, Maine
Output:
my_dict = {'First name': 'Jeff',
'Last name': 'Smith',
.....}
def get_the_deets(path):
doc = Document(path)
parse_list = ['a','b','c','d','e','f','g','h','i','j','k','l']
return {i.text.strip(f' {p}.').split(':')[0]:i.text.strip(f' {p}.').split(':')[1].strip()
for p in parse_list for i in doc.paragraphs if i.text.strip().startswith(f'{p}')}
path = r'path_to_doc'
get_the_deets(path)
This works the way I want it to, but I am looking for criticism as how to clean up my code, as I assume there are more efficient ways of handling this task.
Steps I took:
- create a list of values I am looking for
- Iterate through each paragraph using
doc.paragraph
- Remove whitespace from the the ends of each line
- if the item I am looking for is the first character, split the rest of the line on the
:
- assign the first index of the split to a key, second index to a value
- add strip to the key and value to clean up whitespace and unnecessary characters.