你能解釋一下這段代碼是怎麼回事嗎?我似乎並不瞭解 如何打開文件並逐行讀取它,而不是在for循環中同時讀取所有句子。由於python3打開文件和讀取行
比方說,我有一個文檔文件,這些句子:
cat:dog:mice
cat1:dog1:mice1
cat2:dog2:mice2
cat3:dog3:mice3
下面是代碼:
from sys import argv
filename = input("Please enter the name of a file: ")
f = open(filename,'r')
d1ct = dict()
print("Number of times each animal visited each station:")
print("Animal Id Station 1 Station 2")
for line in f:
if '\n' == line[-1]:
line = line[:-1]
(AnimalId, Timestamp, StationId,) = line.split(':')
key = (AnimalId,StationId,)
if key not in d1ct:
d1ct[key] = 0
d1ct[key] += 1
此答案對我有幫助。謝謝:) – KestutisIT