我與Python的經驗是有限的,所以我一直在使用其他StackOverflow的問題/解答,指導我的劇本,主要是這一個:Python: Comparing two CSV files and searching for similar items這一個:How to Delete Rows CSV in python
我試圖從兩個ID匹配獨立的CSV每一個大體類似:Python腳本語法錯誤
ID trip date location
1 1 1/1/2009 384
1 2 1/3/2009 384
1 3 1/7/2009 467
2 1 1/2/2009 842
2 2 1/3/2009 362
我想根據每個ID需要的車次相匹配,所以在csv1 ID 1我期待在CSV2有1/1上一趟所有ID/2009從位置384開始,然後從該列表中查找哪些人也從位置384開始了1/3/2009的行程,依此類推,直到csv2中只有一個ID與csv1中的ID匹配:一個匹配。下面是我的代碼有:
import csv, sys, fileinput
f1 = open('personal2009.csv', 'rb')
f2 = open('company2009.csv', 'rb')
c1 = csv.reader(f1)
c2 = csv.reader(f2)
vmslist = [row for row in c2]
matchDict = {}
ID_list = []
ID = 0
for log_row in c1:
if log_row[0] != ID:
ID = log_row[0]
matchlist = csv.writer(open("matchlist" + str(ID) + ".csv", "wb")
for vms_row in vmslist:
if vms_row[2] == log_row[2] and vms_row[3] == log_row[3]:
matchlist.writerow(vms_row)
elif log_row[0] in ID_list:
continue
else:
f = fileinput.input("matchlist" + str(ID) + ".csv", inplace=True)
w = csv.writer(sys.stdout)
for match_row in csv.reader(f):
if match_row[2] == log_row[2] and match_row[3] == log_row[3]:
w.writerow(row)
if len(list(w)) == 1:
matchDict[str(ID)] = match_row[0]
vessel_list.append(str(ID))
f1.close()
f2.close()
matchlist.close()
每當我試着調試或運行在PythonWin的代碼,我得到無法運行腳本錯誤- 語法錯誤 - 無效語法中的PythonWin和光標的頁腳停在行:for vms_row in vmslist:
我沒有得到任何進一步的解釋或錯誤信息。我試圖重命名所有的變量,沒有任何東西能夠通過這個錯誤,所以我必須得出結論,我正在嘗試做一些令人難以置信的愚蠢的事情,我看不到它是什麼。有什麼想法嗎?
上面一行中有一個缺失的close-paren。 –