2017-02-14 71 views
0

我試圖讀取python中文件的第5列。如果第三列匹配「Plop」,我將第三列存儲在list1中,否則如果第五列匹配「toto」,我將第三列存儲在list2中。然後我所做的只是檢查兩個列表中每個元素的長度。當我運行我的代碼,我得到這個錯誤:將列表與txt文件中的列進行比較

if word1 in columns[:4] 
        ^
SyntaxError: invalid syntax 

我的代碼如下:

word1=['Popo'] 
word2=['toto'] 
aList1 = list() 
aList = list() 

for line in open("test.txt"): 
    columns = line.split(" ") 
#columns.lookup([toto]) 
    if word1 in (columns[:4]): 
     aList1.insert(columns[:2]) 
    if word2 in (columns[:4]): 
     aList.insert(columns[:2]) 

#print '\n'.join(aList1) 

for entry in aList1: 
    try: 
     l = len(entry) 
     print "Length of", entry, "is", l 
    except: 
     print "Element", entry, "has no defined length" 

for entry in aList: 
    try: 
     l = len(entry) 
     print "Length of", entry, "is", l 
    except: 
     print "Element", entry, "has no defined length" 
+0

而你的代碼沒有正確的縮進! – Arman

+0

@Arman我的代碼在最後2個循環中有正確的縮進,這只是在stackoverflow上我必須爲每行實際輸入4個空格 – user3022048

+0

@ user3022048只需複製/粘貼整個事物,突出顯示所有內容並點擊在編輯器中的{}'按鈕上,或者使用Ctrl + k – roganjosh

回答

2

你缺少到底,應該是:

if word1 in columns[:4]: 
+0

感謝您的回答。它解決了我遇到的語法錯誤。 – user3022048

相關問題