代码之家  ›  专栏  ›  技术社区  ›  Megatron

如何从文本文件中提取特定电子邮件

  •  1
  • Megatron  · 技术社区  · 7 年前

    python新手,坚持这一点!

    我有一个很大的文本文件,里面只有来自不同领域的电子邮件。假设我只想退出gmail和hotmail。

    filename = input('Enter filename to open: ')
    try:
        filename = open(filename)
    except:
        print('File cannot be opened: ', filename)
    exit()
    import re
    for line in filename:
        line = line.rstrip()
        x = re.findall('\S+@gmail.com',  line)
        if len(x) > 0:
            print(x)
        y = re.findall('\S+@hotmail.com',  line)
        if len(y) > 0:
            print(y)
    

    我的目标是让它打印出所有的gmail电子邮件,然后列出它找到的gmail电子邮件地址的数量。然后我希望它列出所有的hotmail帐户,并列出它找到了多少hotmail帐户。有道理?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Taku    7 年前

    @JAW对这个问题绝对正确,因为你正在逐行搜索它。因为你正在使用 re.findall ,没有理由需要遍历这些行。你所要做的就是:

    import re
    
    filename = input('Enter filename to open: ')
    
    try:
        file = open(filename)
    except:
        print('File cannot be opened: ', filename)
        exit()
    
    emails = file.read()
    x = re.findall('\S+@gmail.com',  emails)
    if len(x) > 0:
        print(x)
        # or print("\n".join(x)) for list-like printing 
    
    y = re.findall('\S+@hotmail.com',  emails)
    if len(y) > 0:
        print(y)
        # or print("\n".join(y)) for list-like printing
    
        2
  •  -1
  •   DYZ    7 年前

    gmail = []
    hotmail = []
    
    for line in filename: #filename is a BAD name for this variable
        address = re.findall('\S+@gmail.com', line)
        if address: gmail.extend(address)
        address = re.findall('\S+@hotmail.com', line)
        if address: hotmail.extend(address)
    
    print(gmail)
    print(hotmail)