簡體   English   中英

Python-用數字替換列表中的電子郵件

[英]Python - Replace email from list by numbers

我想用隨機數字替換文本文件中的所有電子郵件地址。 現在,我已經找到了那些電子郵件,但是它們都通過正則表達式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()顯式強制列表為字符串,但是失敗了。

通過讓re模塊為您完成所有工作,避免了轉換列表對象的問題。 re.sub或regex模式object.sub將用以regex匹配對象作為輸入的函數的輸出替換與您的模式匹配的子字符串。

#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 ) )

嘗試遍歷電子郵件並替換,例如:

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()))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM