Trying to pull emails from large docx with Python Docx

Viewed 68

Newbie here.

I am trying to save myself hours of work manually going through a large word document to pull out all the emails.

So far I created this little script:

import re
from docx import Document

document = Document('directory.docx')

email_list = []

for para in document.paragraphs:
    emails = re.findall(r'[\w\.-]+@[\w\.-]+', para.text)
    if emails:
        with open('your_file.txt', 'w') as f: 
          for item in emails:      
             f.write("%s\n" % item)      
    else:
        print("email not found")

Unfortunately I am only getting "Email not found" although there are many emails in the document. The Regular expression I believe is correct.

1 Answers

You did:

  for para in document.paragraphs:
    emails = re.findall(r"[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+", r"para")

which mean you instructed findall to search in r"para" string, whilst you probably mean para variable, please try changing your code to

  for para in document.paragraphs:
    emails = re.findall(r"[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+", para)

and write what effect you get

Related