繁体   English   中英

如何修复 IndexError:字符串索引超出范围 - Python

[英]How to fix IndexError: String index out of range - Python

我正在尝试为我的文本冒险制作一个解析器。 我使用了一个名为test.txt的文本文件。 我不断收到IndexError: string index out of range 我怎样才能解决这个问题?

解析器.py

def parse(file):
  data = {}
  
  with open(file, "r") as f:
    lines = f.readlines()
    f.close()

  for line in lines:
    line = line.strip()
    
    if line[0] == "@":
      name = line[1:]
      name = name.replace("\n", "")

      data[name] = {}

    if line[0] == "-":
      prop = line.split(":")
      prop_name = prop[0].replace("-", "")
      prop_name = prop_name.replace("\n", "")
      
      prop_desc = prop[1][1:]
      prop_desc = prop_desc.replace("\n", "")

      data[name][prop_name] = prop_desc

    

  return data
      
    
print(parse("test.txt"))

测试.txt

@hello

  -desc: Hello World! Lorem ipsum
  -north: world

@world

  -desc: World Hello! blah
  -south: hello
  

您正在剥离换行符( line = line.strip() ),因此如果一行为空,则只有一个空字符串并且line[0]超出范围。

您应该测试该行是否真实:

if line and line[0] == "-":

或者,更好的是,在循环的开头,跳过空行:

for line in lines:
    if line == '\n':
        continue
    # rest of code

由于您的文本中有许多“\n”,因此您应该在文件读取时忽略它们。 尝试这个:

  with open(file, "r") as f:
    lines = f.readline().splitlines()
    f.close()

暂无
暂无

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

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