Python Forum

Full Version: Python beginner that needs an expression added to existing script
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a python script that scrubs emails and works well.

I need to add the ability to remove everything including and after the string "Still have questions" after the second def of "removte_http_links" in the following part of the script.

def extract_http_links(payload):
    # pattern = r'https?://[^\s<>"]+|www\.[^\s<>"]+'
    pattern = r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+=]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
    http_links = re.findall(pattern, payload)
    return http_links

def remove_http_links(payload):
    #pattern = r'https?://[^\s<>"]+|www\.[^\s<>"]+'
    pattern = r'<http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+=<>]|[\r\n]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
    payload_without_links = re.sub(pattern, '', payload)
    pattern = r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+=<>]|[\r\n]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
    payload_without_links = re.sub(pattern, '', payload_without_links)
    return payload_without_links
NEW EXPRESSION TO BE PUT IN HERE IN THE PROCESS

def send_all_email(message_all , subject):
    print(subject)
    print(message_all.encode('utf-8'))
    msg = MIMEMultipart()
    msg['From'] = username
    msg['To'] = forward_address
#   msg['Subject'] = subject
    msg.attach(MIMEText(message_all))
    mail = smtplib.SMTP(smtp_server, smtp_port)
    mail.ehlo()
    mail.starttls()
    mail.ehlo()
    mail.login(username, password)
    mail.sendmail(username, forward_address, msg.as_string())
    mail.quit()
I would appreciate any input to accomplish this task in the sequence above.

Thanks in advance.

Mark
I presume your email is a text file or string. A simple way to achieve this is .split()

myemail = """
All kinds of email info here

https://python-forum.io/thread-40619.html

I was visiting friends in Princeton one Saturday in the 1950s when our
host asked his son-in-law, Bill Bennett, and me (Bruce) if we’d like to
spend the evening with his friend, Albert Einstein. Two awed physics grad-
uate students soon waited in Einstein’s living room as he came downstairs
in slippers and sweatshirt. I remember tea and cookies but not how the
conversation started.

Still have Questions

Einstein soon asked about our quantum mechanics course. He
approved of our professor’s choice of David Bohm’s book as the text, and
he asked how we liked Bohm’s treatment of the strangeness quantum
theory implied.
"""

result = myemail.split('Still have Questions')[0]