[英]Why does my information extraction Python code get wrong output?
我有一個csv文件,我想提取一些統計信息,所以我編寫了一個代碼以輸出每個用戶ID的每個活動的總數,但是該代碼只是正確輸出了第一個ID的信息。有人可以告訴我這是怎么回事我的代碼?這是我的代碼,輸出錯誤。謝謝。
from collections import Counter
import csv
reader=csv.reader(file('F:\\HJZL\PythonData\log_train.csv','rb')) #read the csv file
list1=[] #create an empty list
def static(i): #information extraction function
for line in reader:
if line[0]==str(i):
list1.append(line[3]) #add activities into list
print 'ID:',i,Counter(list1) #print the statistical information of ID i
list1[:]=[] #clear the list
return list1
i=1
while i<4: #get the statistical information of ID1 to ID3
static(i)
i=i+1
print 'end'
為什么ID2和ID3的信息為空?
csv.reader()
對象從基礎文件對象讀取數據,並且文件對象的文件位置在讀取時csv.reader()
移動。 如果要再次閱讀,則需要將文件指針倒回開始處:
with open('F:\\HJZL\PythonData\log_train.csv','rb') as csvfile:
reader = csv.reader(csvfile)
# ...
while i < 4:
static(i)
csvfile.seek(0)
i += 1
但是,最好只從文件中檢索一次信息 。 您可以轉置您的列:
with open('F:\\HJZL\PythonData\log_train.csv','rb') as csvfile:
reader = csv.reader(csvfile)
columns = zip(*reader)
for i, col in enumerate(columns[1:4]):
print 'ID:', i, Counter(col)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.