【问题标题】:Python - Replace email from list by numbersPython - 用数字替换列表中的电子邮件
【发布时间】:2017-01-25 04:44:46
【问题描述】:

我想用随机数替换文本文件中的所有电子邮件地址。现在我找到了这些电子邮件,但它们都由正则表达式 re.findall() 以列表形式返回

例如,输出是这样的:

['xyz123@gmail.com']

所以当我尝试用随机数替换这个输出时,我会得到错误提示

Can't convert 'list' object to str implicitly

我的代码在这里:

with open('a.txt', 'r') as file1:
    with open('b.txt', 'w') as file2:
        for line in file1:
            email = re.findall(......,line)
            file2.write(line.replace(email, random.random()))

其余代码在这里没有用处,因此省略。那么谁能告诉我如何处理这个列表?我试图用 str() 显式地将列表强制转换为字符串,但它失败了。

【问题讨论】:

    标签: python list io


    【解决方案1】:

    通过让 re 模块为您完成所有工作来避免转换列表对象的问题。 re.sub 或正则表达式模式 object.sub 会将与您的模式匹配的子字符串替换为以正则表达式匹配对象作为输入的函数的输出。

    #pass each line through this:
    def mask_matches( string, regex ):
        ''' substrings of string that match regular expressions pattern object regex
        are replaced with random.random( ).
        '''
        def repl( mobj ):
            replacement = random.random( )
            return( replacement )
        return( regex.sub( repl, string ) )
    
    #so if `email` is your regex pattern object, thenyour last line looks something like this:
    file2.write( mask_matches( line, email ) )
    

    【讨论】:

    • 感谢您。但我会在“return(regex.sub(repl, string))
    • 正如我试图在代码注释中解释的那样,我建议的代码中的email 并不是指您的email list()。抱歉,我做得不够远,您无法复制和粘贴。 email 应该是一个正则表达式模式对象。首先,您无需生成列表。而不是以email = re.findall 开头的行,您应该有一个以email = re.compile 开头的行。您没有显示您的正则表达式模式,因此我无法编写复制和粘贴代码来替换该行。
    【解决方案2】:

    尝试通过电子邮件循环并替换,如下所示:-

    with open('a.txt', 'r') as file1:
        with open('b.txt', 'w') as file2:
            for line in file1:
                email = re.findall(......,line)
                for em in email:
                    file2.write(line.replace(em, random.random()))
    

    【讨论】:

    • 谢谢。但是我已经尝试过了,它返回“无法将'float'对象隐式转换为str”
    • 我没有执行这个,是的,可能问题就在这里。我们需要更改最后一行。像这样使用它并获得成功执行 line.replace(em, random.random()) 在下一行 file2.write(STR(line))
    猜你喜欢
    • 2017-12-11
    • 2016-03-30
    • 1970-01-01
    • 2014-09-27
    • 2021-09-02
    • 2015-06-18
    • 1970-01-01
    • 2017-08-13
    • 2018-01-04
    相关资源
    最近更新 更多