0

このコードを使用して、特定のファイル内の電子メールを検索し、それらを別のファイルに書き込みます。メールが重複しないように「in」演算子を使用しました。ただし、このコードは行の後に実行されません for line in f:。私がここで犯した間違いを誰かが指摘できますか?

tempPath = input("Please Enter the Path of the File\n")
temp_file = open(tempPath, "r")
fileContent = temp_file.read()
temp_file.close()

pattern_normal = re.compile("[-a-zA-Z0-9._]+@[-a-zA-Z0-9_]+.[a-zA-Z0-9_.]+")

pattern_normal_list = pattern_normal.findall(str(fileContent))

with open('emails_file.txt', 'a+') as f:            
    for item in pattern_normal_list:            
        for line in f:
            if line in item:
                print("duplicate")
            else:
                print("%s" %item)
                f.write("%s" %item)
                f.write('\n')
4

2 に答える 2

1

新しいソリューション:

tempPath = input("Please Enter the Path of the File\n")
temp_file = open(tempPath, "r")
fileContent = temp_file.read()
temp_file.close()

pattern_normal = re.compile("[-a-zA-Z0-9._]+@[-a-zA-Z0-9_]+.[a-zA-Z0-9_.]+")

addresses = list(set(pattern_normal.findall(str(fileContent))))
with open('new_emails.txt', 'a+') as f:
    f.write('\n'.join(addresses))

私はあなたの論理間違っていたと思います、これはうまくいきます:

addresses = ['test@wham.com', 'heffa@wham.com']

with open('emails_file.txt', 'a+') as f:
    fdata = f.read()
    for mail in addresses:
        if not mail in fdata:
            f.write(mail + '\n')

コードをあまり読まないと、1行ずつループしているように見えます。ループしているアドレスがその行に存在するかどうかを確認し、電子メールを追加していない場合はどうでしょうか。ただし、100行の99%ではアドレスが行に含まれないため、不要な追加が発生します。

私のコードスニペットの出力:

[Torxed@faparch ~]$ cat emails_file.txt 
test@wham.com
Torxed@whoever.com
[Torxed@faparch ~]$ python test.py 
[Torxed@faparch ~]$ cat emails_file.txt 
test@wham.com
Torxed@whoever.com
heffa@wham.com
[Torxed@faparch ~]$ 
于 2013-02-07T11:08:43.887 に答える
-2
for line in f:

最初にf.readlines()を呼び出すべきではありませんか?

lines = f.readlines()
for line in lines:

これをチェックして。

于 2013-02-07T11:13:29.133 に答える