Pytanie o return w funkcji

0

Hej

Napisałem prosty skrypt wyszukujący adresy email w podanym tekście z użyciem regex. Kod:

import re

email_pattern = re.compile(r'\w*\@\w*\.\w*')

email_text = '''
                This is an [email protected].
                And this is one more [email protected].
                This is an [email protected].
                And this is one more [email protected].
                This is an [email protected].
                And this is one more [email protected].
             '''          

def find_email(pattern, text):
    """
    
        Looks for email addresses in given string.
    
    """
    for match in re.finditer(pattern, text):
        start = match.start()
        end = match.end()
        group = match.group()
        print('Found an email: ' + match.group())
        
result = find_email(email_pattern, email_text)
print(result)

Wynikiem tej funkcji jest:
1.png

O co chodzi z tym None? W funkcji brakuje return, czyli funkcja nic nie zwraca, dlatego wyskakuje ten None. Ale jeśli wyrzucę printa i dam return to wtedy printuje mi tylko jeden wynik, pierwszy, na który natrafi i program się kończy. Jak umieścić w funkcji ten return, żeby zwracało mi wszystkie maile bez None?

3

Możesz np dodawać je do jakiegoś stringa wynikowego z \n na końcu każdego i odesłać returnem albo skorzystać z tzw generatora. yield zwraca wartość, ale potem wraca do tego miejsca, więc może szukać następnego. oto twój kod przerobiony na generator:

import re

email_pattern = re.compile(r'\w*\@\w*\.\w*')

email_text = '''
                This is an [email protected].
                And this is one more [email protected].
                This is an [email protected].
                And this is one more [email protected].
                This is an [email protected].
                And this is one more [email protected].
             '''          

def find_email(pattern, text):
    """

        Looks for email addresses in given string.

    """
    for match in re.finditer(pattern, text):
        start = match.start()
        end = match.end()
        group = match.group()
        yield ('Found an email: ' + match.group())

for mail in  find_email(email_pattern, email_text):
    print(mail)

1 użytkowników online, w tym zalogowanych: 0, gości: 1