文件到字典,无法运行程序

2024-09-27 20:19:07 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试着写一段代码,从一个文件中提取文本,移动到一个字典中,然后处理它。我经常会遇到这样的错误:

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

Tags: in文本错误lineitemfileprintblank
3条回答
    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

好吧,你至少应该把这句冒犯的话打印出来,这样你就知道罪魁祸首是什么了:

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 

您的问题是,当文件中有空行时,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将只包含文件最后一行的信息。你知道吗

相关问题 更多 >

    热门问题