繁体   English   中英

Python将文件读取到字典

[英]Python reading file to dictionary

templist=[]
temp=[]
templist2=[]
tempstat1={}
station1={}
station2={}
import os.path 

def main():

    #file name=animallog.txt       
    endofprogram=False 
    try:
        filename=input("Enter name of input file >")
        file=open(filename,"r")
    except IOError:
        print("File does not exist")
        endofprogram=True

    for line in file:
        line=line.strip('\n')

        if (len(line)!=0)and line[0]!='#':          
            (x,y,z)=line.split(':')

            record=(x,z)

            if record[0] not in station1 or record[0] not in station2:

                if record[1]=='s1' and record[0] not in station1:
                    station1[0]=1

                if record[1]=='s2' and record[0] not in station2:
                    station2[0]=1

            elif record[0] in station1 or record[0] in station2:

                if record[1]=='s1':
                    station1[0]=station1[0]+1
                elif record[1]=='s2':
                    station2[0]=station2[0]+1 

    print(station1)
    print(station2)

main()

嗨,大家好!

我当时正在开发一个程序,该程序从以下格式的文件读取:GIVEN AT THE BOTTOM

但由于某些原因的输出为{0:1}两者station1station2 我只是想知道为什么会这样? 我尝试使用调试功能,但无法理解。 感谢您的所有努力! 谢谢 :)

FILE FORMAT:
(NAME:DATE:STATION NUMBER)

a01:01-24-2011:s1

a03:01-24-2011:s2

a03:09-24-2011:s1

a03:10-23-2011:s1

a04:11-01-2011:s1

a04:11-02-2011:s2

a04:11-03-2011:s1

a04:01-01-2011:s1

您的词典仅包含{0:1}因为这就是您要放入的所有内容!

station1[0]=1 # This sets a key-value pair of 0 : 1

我不确定您的预期输出是什么,但我认为您正在使此工作变得比所需的更加困难。 我猜你想要这样的东西:

name, date, station = line.split(':') # use meaningful identifiers!

if name not in station1 and station == 's1':
    station1[name] = date
elif name not in station2 and station == 's2':
    station2[name] = date

这将为您提供输出字典,如下所示:

{'a01' : '01-24-2011',
 'a03' : '09-24-2011'}

请注意,通过检查键是否已在字典中,您只会将遇到的任何非唯一键中的第一个添加到任何给定的字典中(例如,您只会得到四个'a04'的前两个) 'a04'在你的榜样输入的条目-后两个将被忽略,因为'a04'已经在这两个dicitonaries)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM