2014-11-21 177 views
1

我想比較兩個能像下面比較兩個CSV文件,並打印在不同的Python

English.csv 
i 
am 
is 
was 
were 

Dictionary.csv 
i,insomnia 
d,disease 
bc,breast cancer 

我想第一列中比較兩個文件和打印的CSV文件中的行如下所示的不同於Dictionary.csv的行

final.csv 
d,disease 
bc,breast cancer 

我試過這段代碼。

import csv 
with open('English.csv', 'rb') as csvfile1: 
    with open ("Dictionary.csv", "rb") as csvfile2: 
     reader1 = csv.reader(csvfile1) 
     reader2 = csv.reader(csvfile2) 
     rows1 = [row for row in reader1] 
     rows2 = [row for row in reader2] 
     col_a = [row1[0] for row1 in rows1] 
     col_b = [row2[0] for row2 in rows2] 
     col_c = [row2[1] for row2 in rows2] 
     only_b = [text for text in col_b if not text in col_a] 

我可以從第一列中得到不同的數據,但不是像下面這樣的第二列。我如何從第二欄中獲取相應的數據?

>>>only_b 
['d','bc'] 

回答

1

不知道如何有效的就是這一點,但IMO你想要做什麼:

import csv 
with open('English.csv', 'rb') as csvfile1: 
    with open ("Dictionary.csv", "rb") as csvfile2: 
     reader1 = csv.reader(csvfile1) 
     reader2 = csv.reader(csvfile2) 
     rows1_col_a = [row[0] for row in reader1] 
     rows2 = [row for row in reader2] 
     only_b = [] 
     for row in rows2: 
      if row[0] not in rows1_col_a: 
       only_b.append(row) 
     print only_b 

輸出:

[['d', 'disease'], ['bc', 'breast cancer']] 
相關問題