2013-11-26 4 views
0

그래서 파일에서 텍스트를 가져 와서 사전으로 이동 한 다음 처리하는 코드를 작성하려고합니다. 이 오류가 계속 :사전에 파일을 실행할 수 없습니다.

File "C:\Users\Oghosa\Assignment2.py", line 12, in <module> 
builtins.IndexError: string index out of range 

여기 내 프로그램입니다 :

endofprogram = False 
dic = {} 
try: 
    filename = input("Please Enter the Filename:") 
    infile = open(filename, 'r') 
except IOError: 
    print("Error Reading File! Program ends here!") 
    endofprogram = True 
if endofprogram == False: 
    for line in infile: 
     line = line.strip("\n") 
     if (line != " ") and (line[0] != "#"): 
      item = line.split(":") 
      print(items) 
      dic["Animal id"] = item[0] 
      dic["Date"] = item[1] 
      dic["Station"] = item[2] 
     print(dic) 

하시기 바랍니다 내 실수를 지적 누군가의 도움이 수 있습니까?

다음은 샘플 입력 텍스트는 다음과 같습니다

#Comments 
a01:01-24-2011:s1 
a03:01-24-2011:s2 
    <blank line> 
    <blank line> 
a02:01-24-2011:s2 
a03:02-02-2011:s2 
a03:03-02-2011:s1 
a02:04-19-2011:s2 
    <blank line> 
#comments 
a01:05-14-2011:s2 
a02:06-11-2011:s2 
a03:07-12-2011:s1 
a01:08-19-2011:s1 
a03:09-19-2011:s1 
a03:10-19-2011:s2 
a03:11-19-2011:s1 
a03:12-19-2011:s2 
+0

당신은 우리에게 입력 파일 샘플을 줄 수 있습니까? – Christian

+0

@Christian 여기에 animallog.txt라고하는 사람이 있습니다. – user2767528

+0

댓글을 달거나 게시물을 편집해서 올려 놓지 마십시오. 포맷이 올바른지 확인하십시오. – Christian

답변

0

당신이 당신의 파일에 빈 줄이 있습니까? 12 번째 줄에서 line[0]을 사용하여 줄을 만들기 전에 줄에 텍스트가 있는지 확인하기를 원할 수 있습니다. 당신이 정말로 12 라인한다의 빈 문자열이있는 라인이 있나요 정말 읽어

if line.strip() and (line[0] != "#"): 

편집 .. 전체 예제를 추가. 당신이 범인이 무엇인지 알 수 있도록

dic = {} 
filename = input("Please Enter the Filename:") 
try: 
    infile = open(filename, 'r') 
except IOError: 
    print("Error Reading File! Program ends here!") 
else: 
    for line in infile: 
     line = line.strip() 
     if line and line[0] != "#": 
      item = line.split(":") 
      dic["Animal id"] = item[0] 
      dic["Date"] = item[1] 
      dic["Station"] = item[2] 
+0

빈 문자열이 있습니다. 정확히 3 . 나는 그 (것)들을 원래 포스트에서 지정했다. 감사합니다 – user2767528

+0

진위 검사 전에 공백을 문자열로 변환했습니다. – dstanek

+0

감사합니다. 그걸 고쳐서, 왜 내가 이전 코드가 작동하지 않았는지 물어봐도 될까?> – user2767528

0

글쎄, 당신은 적어도 잘못된 라인을 인쇄해야합니다 :

for line in infile: 
    items = line.strip("\n") 
    try: 
     if (line.strip != "") and (items[0] != "#"): 
      items = line.split(":") #i dont like your reuse of line so changing to items 
      .... 
    except IndexError: #if python 3 use except IndexError as e: 
     print(items) #prints offending line 
0
endofprogram = False 
    attrs=["Animal id","Date","Station"] 
    dictionary=[] 
    try: 
     # filename = input("Please Enter the Filename:") 
     infile = open('rite.txt', 'r') 
    except IOError: 
     print("Error Reading File! Program ends here!") 
     endofprogram = True 
    if endofprogram == False:  
     for line in infile: 
      line = line.strip("\n") 

      if (line != "") and (line[0] != "#"): 
       item = line.split(":") 
       dictionary.append(dict(zip(attrs, item))) 
    print dictionary 
0

귀하의 문제는 그 파일에 빈 줄, line[0] 아무튼이있을 때 존재하지 않습니다. 이 문제는이 버전을 사용해 해결하려면 : 주목할 가치가

endofprogram = False 
dic = {} 
try: 
    filename = input("Please Enter the Filename:") 
    infile = open(filename, 'r') 
except IOError: 
    print("Error Reading File! Program ends here!") 
    endofprogram = True 
if endofprogram == False: 
    for line in infile: 
     line = line.strip("\n") 
     if len(line): 
      if line[0] != "#": 
       item = line.split(":") 
       print(items) 
       dic["Animal id"] = item[0] 
       dic["Date"] = item[1] 
       dic["Station"] = item[2] 
      print(dic) 

당신이 루프의 각 반복에 dic을 덮어 쓰는 것입니다. 그래서 루프가 끝난 후에; dic에는 파일의 마지막 줄에있는 정보 만 포함됩니다.

0

문제는 당신이

if (line != " ") and (line[0] != "#"): 

문에 제대로 빈 줄을 검사되지 않은 것입니다. 이는 line = line.strip("\n")이 실행 된 후에도 공간이 남아 있지 않기 때문에 인덱싱 작업이 실패하게됩니다.

아래 코드에는 그 외 여러 가지 코딩 오류가 수정되어 있습니다. 사람들이보다 쉽게 ​​당신을 도울 수 있도록 여기에 실제 코드를 게시하는 것이 중요합니다.

endofprogram = False 
dic = {} 
try: 
    filename = input("Please Enter the Filename:") 
    infile = open(filename, 'r') 
except IOError: 
    print("Error Reading File! Program ends here!") 
    endofprogram = True 
if not endofprogram: 
    for line in infile: 
     line = line.strip("\n") 
     if line and line[0] != "#": 
      items = line.split(":") 
      print(items) 
      dic["Animal id"] = items[0] 
      dic["Date"] = items[1] 
      dic["Station"] = items[2] 
    print(dic) 
관련 문제