小编use*_*308的帖子

python3打开文件和阅读行

你能解释一下这段代码中发生了什么吗?我似乎不明白你如何打开文件并在for循环中逐行读取而不是所有句子.谢谢

假设我在文档文件中有这些句子:

cat:dog:mice
cat1:dog1:mice1
cat2:dog2:mice2
cat3:dog3:mice3
Run Code Online (Sandbox Code Playgroud)

这是代码:

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
Run Code Online (Sandbox Code Playgroud)

python-3.x

6
推荐指数
2
解决办法
3万
查看次数

标签 统计

python-3.x ×1