93|PYTHON – Dream Job?

BYU Student Author: @Nate
Reviewers: @Erick_Sizilio, @Jae
Estimated Time to Solve: 60 Minutes

We provide the solution to this challenge using:

  • Python

Need a program? Click here.

Overview
Congrats! You just found your dream job, and you couldn’t be more excited. For years, you’ve been wanting to get promoted from assistant regional manager to assistant to the regional manager. Well, last week you interviewed with a prestigious paper manufacturer based in Scranton, PA, and the regional manager Michael just called—you got the job!

Michael has already emailed you the employment contract, and you are excited to read through it. However, wanting to save paper and not having time to read all 4 pages, you decide to take a quick hour to write a Python program that can identify the obligations and benefits outlined for you and your prospective employer, Dunder Mifflin, in your employment contract.

You also know that nearly 84% of employees never read their entire employment contracts, so if your program is any good, you might be able to license it out for a healthy profit.

Instructions
In an hour or less, write a script that can identify obligations and benefits outlined for different parties in a contract.

To help you, I have provided your employment contract with Dunder Mifflin as a .pdf, .docx, and .txt file. Pick one or more formats that your script will accept as input from a user.

I have also provided a file containing a list of 50 common words that indicate obligations or benefits in contracts. This file can help you search for and return instances of these words along with the sentences containing them. Output these sentences to a report that you can review to avoid reading the whole contract.

See what obligations and benefits your script finds in the Dunder Mifflin contract and comment your favorites below!

Data Files

Suggestions and Hints

I recommend using Python’s Regex package to parse through contract text and find instances of the words in the contract_words.txt file. Make sure that you are returning entire sentences so that you don’t miss obligations or benefits.

Solution

Solution Code
from pdfminer.high_level import extract_text 
import docx, re, sys 

path = input('Input the full file path of your contract.') # Accept file path 

# Read list of contract words  
with open('contract_words.txt', 'r') as file: 
    regex_list = file.readlines() 

# Extract text from .pdf files 
def pdf_extract(path): 
    pdf_file = open(path, 'rb') # Open the PDF file 
    text = extract_text(pdf_file) # Extract text from the PDF 
    pdf_file.close() # Close the PDF file 
    text = text.replace('\n','') 
    return text 

# Extract text from .docx files 
def docx_extract(path): 
    doc = docx.Document(path) # Open the Word document 
    # Extract text from the Word document 
    text = '' 
    for paragraph in doc.paragraphs: 
        text += paragraph.text + ' ' 
    return text

# Read text from .txt files 
def txt_extract(path): 
    with open(path, 'r') as file: 
        text = file.read() # Read the contents of the file 
    text = re.sub(r'\n|\xa0|\t',' ',text) 
    return text 

# Split text into list of sentences 
def split_sentences(text): 
    text = re.sub(r'\s+',r' ',text) 
    sentence_splits = re.compile(r""" 
        # Split sentences on whitespace between them. 
        (?: # Group for two positive lookbehinds. 
        (?<=[.!?]) # Either an end of sentence punct, 
        | (?<=[.!?]['"]) # or end of sentence punct and quote. 
        ) # End group of two positive lookbehinds. 
        \s+ # Split on whitespace between sentences. 
        """,  
        re.IGNORECASE | re.VERBOSE) 
    text_list = sentence_splits.split(text)

    return text_list 
 
# Allow user to reference .pdf, .docx, or .txt files 
if path[-3:] == 'pdf': 
    text = pdf_extract(path) 
elif path[-4:] == 'docx': 
    text = docx_extract(path) 
elif path[-3:] == 'txt': 
    text = txt_extract(path) 
else: 
    # End program if file type unsupported 
    print('The path you have entered is not valid.\nPlease enter a file with a .pdf, .docx, or .txt extension.') 
    sys.exit() 

# Accept titles of parties in contract 
parties = input('List the titles of all parties for whom you want an overview. Separate parties with commas.') 
parties_list = parties.split(',')  

text_list = split_sentences(text) # Split text into sentences  

# Create an output word doc with title 
doc = docx.Document() 
doc.add_paragraph('CONTRACT OVERVIEW:\n')  

# Find obligations/benefits of each party 
for i, party in enumerate(parties_list): 
    # Clean party title 
    party = party.lstrip().rstrip().lower()  
    parties_list[i] = party 
    # Check for party title in contract 
    while party not in text.lower(): 
        # Prompts user if party title not found 
        parties_list[i] = input(f'"{party}" is not referenced in this contract, please provide a new title for this party, or type "END" to cancel.') 
        if parties_list[i].lower() == 'end': 
            sys.exit() 
        party = parties_list[i]  

    output_list = [] # Create list of sentences with obligations/benefits 
    doc.add_paragraph(f'Obligations and Benefits of {party.upper()}:') # Add subtitle for party 
    # Iterate through sentences in contract 
    for t in text_list: 
        # Iterate through contract words 
        for r in regex_list: 
            r = r.replace('\n','') 
            # Find contract word in sentence and append matches to output list 
            if re.search(f'{party}\\s+{r}',t,re.IGNORECASE): 
                output_list.append(t) 
    # Drop duplicates in output list 
    output_set = set(output_list) 
    # Add setences to word doc 
    for o in output_set: 
        doc.add_paragraph(f'{o}\n') 
    # if no obligations found, type 'None' 
    if len(output_set) == 0: 
        doc.add_paragraph('None\n')  

doc.save('Contract Overview.docx') # Save word doc 

Challenge93_Solution.ipynb
Solution Video: Challenge 93|PYTHON – Dream Job?

This employment agreement between Dunder Mifflin and You outlines the following commitments:

  1. Employment and Duties: You will be employed as an Assistant to the Regional Manager at Dunder Mifflin, performing duties as needed, supervised by the company’s personnel.
  2. Best Efforts: You are committed to performing your duties diligently and to the best of your abilities to meet Dunder Mifflin’s expectations.
  3. Compensation: You will receive a specified annual salary, subject to tax withholding, and upon termination, you’ll receive payments for accrued periods and earned commissions.
  4. Expense Reimbursement: Dunder Mifflin will reimburse your out-of-pocket expenses according to their policies.
  5. Confidentiality: You’re obligated to maintain strict confidentiality about company information and not disclose it to third parties.
  6. Unauthorized Disclosure: Dunder Mifflin has the right to seek legal action if you disclose confidential information improperly.
  7. Confidentiality After Termination: The confidentiality obligations persist for two years after your employment ends.
  8. Non-Compete Agreement: You agree not to engage with specific competitors for a duration of 100 years following the termination of your employment within a designated geographical area.
  9. Vacation: You’re entitled to 365 days of paid vacation per year, subject to approval and company policies.
  10. Sick Leave: You have 42 days of unpaid sick leave per year, and unused benefits are forfeited upon termination.
  11. Holidays: You get 10 paid holidays per calendar year in accordance with company policies.
  12. Insurance Benefits: You’re entitled to insurance benefits according to the company’s policies and applicable laws.
  13. Other Benefits: Additional benefits like an annual ski pass, bi-annual llama petting, and a daily bubble gum allowance are provided in line with company policies.
  14. Term/Termination: The initial term of employment is specified, and termination can occur with varying notice periods depending on the initiator and circumstances.
  15. Termination for Disability: The agreement allows termination if you become permanently disabled.
  16. Compliance with Employer’s Rules: You agree to comply with all company rules and regulations.
  17. Notices: Guidelines for delivering official notices between parties.
  18. Entire Agreement: This agreement supersedes any prior agreements, verbal or written.
  19. Amendment: Modifications to this agreement require written consent from both parties.
  20. Severability: In case any part of the agreement is deemed invalid, the rest remains enforceable.
  21. Waiver of Contractual Right: The failure to enforce any provision doesn’t limit the right to enforce it later.
  22. Applicable Law: The agreement is governed by the laws of the State of Delaware.
  23. Signatories: Signed by the Director of Dunder Mifflin and you, indicating acceptance and agreement to the terms.

These commitments cover various aspects of employment, responsibilities, benefits, and obligations between you and Dunder Mifflin.

The employment agreement between you and Dunder Mifflin outlines commitments including Employment and Duties, Best Efforts, Compensation, and Expense Reimbursement. These are some of my favorites especially Reimbursement because Dunder Mifflin will reimburse your out-of-pocket expenses that have to do with their policies and business and that gives security.

  1. Job Role and Duties: You’re hired as an Assistant to the Regional Manager at Dunder Mifflin, taking on tasks as needed and under company supervision.

  2. Diligence Commitment: You commit to performing your duties diligently and to the best of your abilities to meet Dunder Mifflin’s expectations.

  3. Compensation Terms: You’ll receive an annual salary, subject to tax withholding. Upon termination, you’ll receive payments for accrued periods and earned commissions.

  4. Expense Reimbursement: Dunder Mifflin will reimburse your out-of-pocket expenses in accordance with company policies.

  5. Confidentiality Requirement: You must strictly maintain confidentiality about company information and avoid disclosing it to third parties.

  6. Unauthorized Disclosure Consequences: Dunder Mifflin has the right to seek legal action if you improperly disclose confidential information.

  7. Confidentiality After Termination: Confidentiality obligations persist for two years after your employment ends.

  8. Non-Compete Agreement: You agree not to engage with specific competitors for 100 years after the termination of your employment within a designated geographical area.

  9. Vacation Entitlement: You’re entitled to 365 days of paid vacation per year, subject to approval and company policies.

  10. Sick Leave: You have 42 days of unpaid sick leave per year, and unused benefits are forfeited upon termination.

  11. Holiday Entitlement: You receive 10 paid holidays per calendar year following company policies.

  12. Insurance Benefits: You’re entitled to insurance benefits according to the company’s policies and applicable laws.

  13. Additional Benefits: Extra benefits like an annual ski pass, bi-annual llama petting, and a daily bubble gum allowance are provided following company policies.

  14. Term/Termination: The initial term of employment is specified, and termination can occur with varying notice periods depending on the initiator and circumstances.

  15. Termination for Disability: The agreement allows termination if you become permanently disabled.

  16. Compliance with Employer’s Rules: You agree to comply with all company rules and regulations.

  17. Notices Guidelines: Guidelines for delivering official notices between parties.

  18. Entire Agreement: This agreement supersedes any prior agreements, verbal or written.

  19. Amendment Process: Modifications to this agreement require written consent from both parties.

  20. Severability Clause: If any part of the agreement is deemed invalid, the rest remains enforceable.

  21. Waiver of Contractual Right: The failure to enforce any provision doesn’t limit the right to enforce it later.

  22. Applicable Law: The agreement is governed by the laws of the State of Delaware.

  23. Signatories: Signed by the Director of Dunder Mifflin and you, indicating acceptance and agreement to the terms.

Commitments: 1. Employment and Duties: You will be employed as an Assistant to the Regional Manager at Dunder Mifflin, performing duties as needed, supervised by the company’s personnel.
2. Best Efforts: You are committed to performing your duties diligently and to the best of your abilities to meet Dunder Mifflin’s expectations.
3. Compensation: You will receive a specified annual salary, subject to tax withholding, and upon termination, you’ll receive payments for accrued periods and earned commissions.
4. Expense Reimbursement: Dunder Mifflin will reimburse your out-of-pocket expenses according to their policies.
5. Confidentiality: You’re obligated to maintain strict confidentiality about company information and not disclose it to third parties.
6. Unauthorized Disclosure: Dunder Mifflin has the right to seek legal action if you disclose confidential information improperly.
7. Confidentiality After Termination: The confidentiality obligations persist for two years after your employment ends.
8. Non-Compete Agreement: You agree not to engage with specific competitors for a duration of 100 years following the termination of your employment within a designated geographical area.
9. Vacation: You’re entitled to 365 days of paid vacation per year, subject to approval and company policies.
10. Sick Leave: You have 42 days of unpaid sick leave per year, and unused benefits are forfeited upon termination.
11. Holidays: You get 10 paid holidays per calendar year in accordance with company policies.
12. Insurance Benefits: You’re entitled to insurance benefits according to the company’s policies and applicable laws.
13. Other Benefits: Additional benefits like an annual ski pass, bi-annual llama petting, and a daily bubble gum allowance are provided in line with company policies.
14. Term/Termination: The initial term of employment is specified, and termination can occur with varying notice periods depending on the initiator and circumstances.
15. Termination for Disability: The agreement allows termination if you become permanently disabled.
16. Compliance with Employer’s Rules: You agree to comply with all company rules and regulations.
17. Notices: Guidelines for delivering official notices between parties.
18. Entire Agreement: This agreement supersedes any prior agreements, verbal or written.
19. Amendment: Modifications to this agreement require written consent from both parties.
20. Severability: In case any part of the agreement is deemed invalid, the rest remains enforceable.
21. Waiver of Contractual Right: The failure to enforce any provision doesn’t limit the right to enforce it later.
22. Applicable Law: The agreement is governed by the laws of the State of Delaware.
23. Signatories: Signed by the Director of Dunder Mifflin and you, indicating acceptance and agreement to the terms.