Python: сопоставление двух столбцов из двух файлов - PullRequest
0 голосов
/ 26 июня 2018

Я хочу создать скрипт Python, который соответствует первым 2 столбцам из входного файла (файл 1)

10000D 10000R
10003D 10003R

и сопоставляет эти два столбца со столбцами 2 и 4 в другом входном файле (файл 2), где хранится набор данных.

0 10000D 0 10000R 0.05
0 10001D 0 10001D 0.06
0 10003D 0 10003R 0.09

После сопоставления этих столбцов я хотел бы распечатать строки, в которых столбцы из файла 1, которые сопоставлены с файлом 2, сохраняются в новом выходном файле. Выходной файл должен выглядеть так:

0 10000D 0 10000R 0.05
0 10003D 0 10003R 0.09

Мой код выглядит так:

#Python code for pi-hats extraction

#!/usr/bin/python

#open and read file to read from (F1), file to match to (F2), File to write and save to (F3)

F1 = open("File_1", "r") #File_1 is original file, has 2 columns
F2 = open("File_2", "r") #where dataset is kept
F3 = open("File_3", "w") #where matches are stored

for match1 in sorted(F1):
    if match1 in F2:
        F3.write(match)
        F3.close()
exit

Однако, когда я запускаю этот код, я не получаю никаких совпадений.
Есть предложения?

Спасибо

DM

Обновление: Исходный файл 2 выглядит примерно так:

0  10000_D   0  10000_R AB     0  1.2345  0.1234  0.0000  0.0000  -1  0.765432  0.05  1.2345

0  10001_D   0  10001_R AB     0  1.2345  0.1234  0.0000  0.0000  -1  0.876543  0.06  1.3456

0  10003_D   0  10003_R AB     0  1.2345  0.1234  0.0000  0.0000  -1  0.987654  0.09  1.4567

Может быть, интервал как-то связан с этим? Я думаю, что форматирование могло измениться, когда я поставил его в Excel.

1 Ответ

0 голосов
/ 26 июня 2018
import csv

with open("File_1", "r") as F1:  #File_1 is original file, has 2 columns
    # split the file using a space as delimiter and read it to the memory:
    F1_d = sorted(csv.reader(F1, delimiter=' ')) 

with open("File_2", "r") as F2:  #where dataset is kept
    # split the file using space again, and read it to a dictionary
    # structure indexed by second and forth columns:
    F2_d = {(row[1], row[3]): row for row in csv.reader(F2, delimiter=' ')}

with open("File_3", "w") as F3: #where matches are stored
    for match1 in F1_d: 
        if tuple(match1) in F2_d: # search for a match using the index defined
            F3.write(' '.join(F2_d[tuple(match1)]) + '\n')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...