2016-09-13 80 views
0

我想使用queryfile.txt作爲源文件,它將用於搜索每行並將其與datafile.txt進行匹配。但datafile.txt具有不同的結構。使用來自另一個帶扭曲文件的輸入來搜索文件的文本[Python]

queryfile.txt應該是這樣的:

Gina Cooper 

Asthon Smith 

Kim Lee 

而datafile.txt看起來是這樣的:

Gina Cooper 

112 Blahblah St., NY 

Leigh Walsh 

09D blablah, Blah 

Asthon Smith 

another address here 

Kim Lee 

another address here 

我需要後,得到的名稱和行。下面的代碼得到兩個文件中匹配的名字,這是從dstromberg(https://stackoverflow.com/a/19934477)修改代碼:

with open('querfile.txt', 'r') as input_file: 
    input_addresses = set(names.rstrip() for names in input_file) 

with open('datafile.txt', 'r') as data_file: 
    data_addresses = set(names.rstrip() for names in data_file) 

with open('names_address.txt', 'w') as output: 
    names_address=("\n".join(input_addresses.intersection(data_addresses))) 
    output.write(names_address) 

綜上所述,我想在我的OUTFILE(names_address.txt)看到的名字加地址對應於他們的名字,這基本上是下一行。我剛剛在一個月前開始使用python進行遊戲,並且我相信我會卡住。感謝您的幫助。通過選項

with open('datafile.txt', 'r') as data_file: 
    data = data_file.readlines() 
    data_addresses = list(filter(None, [line for line in data if not line[0].isdigit()])) 

回答

0

環代替,然後你可以只抓下一個索引:

+0

Hi @AlbertRothman, 感謝您的建議。 '開放(input_filename, 'R')作爲INPUT_FILE: input_addresses = input_file.readlines() 開放(data_filename, 'R')作爲DATA_FILE我已經使用這個代碼這樣的嘗試: data_addresses = data_file.readlines() 張開( 「emails.txt」, 「W」)作爲輸出: \t爲i的範圍(LEN(data_addresses)): \t \t用於input_addresses條目: \t \t \t如果進入== data_addresses [我]: \t \t \t \t output.write(data_addresses [I] + data_addresses [I + 1])' ,但我不知道它爲什麼不能迭代input_addresses的最後一行。有任何想法嗎? – jfo

+0

嗯,這取決於錯誤是什麼。它看起來應該工作,輸出是意想不到的,你是否得到一個錯誤?你確定它不會到文件末尾嗎?在你的評論中,你已經將呼叫移除了,所以可能只有一些額外的空白。 –

+0

我之前的評論中沒有出現任何錯誤。 如果我使用'data_addresses = [names.rstrip()作爲data_file中的名稱]',它會給我所需的輸出,但不是所需的格式,這是一行不帶空格的值。所以我只是用'output.write(data_addresses [i] +「\ n」+ data_addresses [i + 1] +「\ n」)來改變格式。它看起來不漂亮,但它的工作原理。 對於大型數據集(即十萬行),應該如何使這些代碼更高效? – jfo

0

改寫這個:

with open('datafile.txt', 'r') as data_file: 
    data_addresses = set(names.rstrip() for names in data_file) 

對此

for i in range(len(data_addresses): 
    for entry in input_addresses: 
    if entry==data_addresses[i]: 
     output.write(data_address[i] + data_address[i+1]) 

這可能沒有時間複雜度很高,但您的數據集出現

相關問題