我想完成這個特定的任務,我有 2 個檔案,第一個包含電子郵件和憑據:
[email protected]:Xavier
[email protected]:vocojydu
[email protected]:voluzigy
[email protected]:Pussycat5
[email protected]:xrhj1971
[email protected]:xrhj1971
第二個,帶有電子郵件和位置:
[email protected]:BOSNIA
[email protected]:ROMANIA
我希望,只要在第二個檔案中找到來自第一個檔案的電子郵件,該行就會被 EMAIL:CREDENTIAL:LOCATION 替換,如果找不到,它最終會變成: EMAIL:CREDENTIAL:BLANK
所以最終檔案必須是這樣的:
[email protected]:Xavier:BOSNIA
[email protected]:vocojydu:BLANK
[email protected]:voluzigy:ROMANIA
[email protected]:Pussycat5:BLANK
[email protected]:xrhj1971:BLANK
[email protected]:xrhj1971:BLANK
我在 python 中做了幾次嘗試,但寫它甚至不值得,因為我不太接近解決方案。
問候 !
編輯:
這是我嘗試過的:
import os
import sys
with open("test.txt", "r") as a_file:
for line_a in a_file:
stripped_email_a = line_a.strip().split(':')[0]
with open("location.txt", "r") as b_file:
for line_b in b_file:
stripped_email_b = line_b.strip().split(':')[0]
location = line_b.strip().split(':')[1]
if stripped_email_a == stripped_email_b:
a = line_a ":" location
print(a.replace("\n",""))
else:
b = line_a ":BLANK"
print (b.replace("\n",""))
這是我得到的結果:
[email protected]:Xavier:BOSNIA
[email protected]:Xavier:BLANK
[email protected]:voluzigy:BLANK
[email protected]:voluzigy:ROMANIA
[email protected]:vocojydu:BLANK
[email protected]:vocojydu:BLANK
[email protected]:Pussycat5:BLANK
[email protected]:Pussycat5:BLANK
[email protected]:xrhj1971:BLANK
[email protected]:xrhj1971:BLANK
[email protected]:xrhj1971:BLANK
[email protected]:xrhj1971:BLANK
我非常接近,但我得到了重復;)
問候
uj5u.com熱心網友回復:
重復問題來自這樣一個事實,即您正在以嵌套方式讀取兩個檔案,一旦test.txt讀取了其中的一行,您就可以打開該location.txt檔案進行讀取并對其進行處理。然后,您從 中讀取第二行test.txt,然后重新打開location.txt并再次處理它。
相反,從 中獲取所有必要的資料location.txt,例如,放入字典中,然后在閱讀 時使用它test.txt:
email_loc_dict = {}
with open("location.txt", "r") as b_file:
for line_b in b_file:
splits = line_b.strip().split(':')
email_loc_dict[splits[0]] = splits[1]
with open("test.txt", "r") as a_file:
for line_a in a_file:
line_a = line_a.strip()
stripped_email_a = line_a.split(':')[0]
if stripped_email_a in email_loc_dict:
a = line_a ":" email_loc_dict[stripped_email_a]
print(a)
else:
b = line_a ":BLANK"
print(b)
輸出:
[email protected]:Xavier:BOSNIA
[email protected]:vocojydu:BLANK
[email protected]:voluzigy:ROMANIA
[email protected]:Pussycat5:BLANK
[email protected]:xrhj1971:BLANK
[email protected]:xrhj1971:BLANK
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/358681.html
