2014-04-01 97 views
0
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() 

嗨,大家好!Python阅读文件到字典

我只是一个程序,它从这种格式的文件读取的工作:考虑在底部

但由于某些原因输出{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

我想你想使用station1 [record [0]]而不是station1 [0],station2相同 – kostya

+0

是的,我在此之前修好了!发现我的错误,但感谢您的帮助:) – Newbie

回答

1

你的字典只持有{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'已经是在两个dicitonaries)。

+0

嗨!我看到了,仍然感觉很蠢。非常感谢你:) – Newbie