字符串索引超出范围python 3.7

时间:2018-12-01 22:42:40

标签: python python-3.x

我正在尝试为文本rpg游戏编写一个函数,该函数将在终端上打印特定标记中的所有内容,但我不断收到此错误消息:

IndexError: string index out of range

文件中的标记文本如下:

  

| d0Dyspergator:   “ Pulveres es et in寻常粉红色”   Raz na dwie walki i Tylko raz w walce pozwala nauniknięcienastępnegoataku przeciwnika   poprzez chwilowe zamienienieCięw atomowypył。|

管道及其后的前两个符号开始标记,下一个管道终止它。 这是代码:

def bard(paragraph, point, file):
    with open(file, 'r', encoding='utf-8') as w:
        d = w.read()
        index = 0
        tab = []
        frag = 0
        while frag == 0:
            if d[index] == '|'and d[index + 1] == paragraph and d[index + 2] == point:
                while d[index+3] != '|' and index + 3 <= len(d):
                    tab.append(d[index+3])
                    index += 1
                frag += 1
            else:
                index += 1
        a = ''.join(tab)
        print(a)
    return

我将非常感谢您的帮助,我是编程新手,可能犯了一个愚蠢的错误。

2 个答案:

答案 0 :(得分:3)

您正在尝试对文本进行模式匹配。听说过regular expression吗?

这正是它们构建的目的:

text = """This is some text.
|2. second 
thing| more text
|3. thingding is after the marker and this text also.
This texts ends what I want| and this text should not be found..
also not found."""
with open("t.txt","w") as  f: 
    f.write(text)

程序:

with open("t.txt") as r:
    data = r.read()

import re
pattern = r'\|\d+\..*?\|'
k = re.findall(pattern,data,re.MULTILINE|re.DOTALL)

print(k)

输出:

['|2. second \nthing|', 
 '|3. thingding is after the marker and this text also.\nThis texts ends what I want|']

我使用的模式r'\|\d+\..*?\|'寻找:

\|          matches the character | literally (case sensitive)
\d+         matches a digit (equal to [0-9])
    +           Quantifier — one to unlimited times, as many as possible
\.          matches the character . literally (case sensitive)
.*?         matches any character 
    *?          Quantifier — zero to unlimited times, as few as possible 
\|          matches the character | literally (case sensitive)

您可以在此处使用它:https://regex101.com/r/65R2gq/1/

如果只需要文本,则可以使用捕获组-将模式更改为

pattern = r'\|\d+\.(.*?)\|'

获得

[' second \nthing', 
 ' thingding is after the marker and this text also.\nThis texts ends what I want']

答案 1 :(得分:0)

假设a)具有堆积和前两个(恰好两个)字符的数据结构是您自己开发的格式,并且您可以控制它被一致使用,那么您实际上不需要进行任何操作最少使用regular expressions

foo = '|d0Dyspergator: "Pulvis es et in pulverem revertis" Raz na dwie walki i tylko raz w walce pozwala na uniknięcie następnego ataku przeciwnika poprzez chwilowe zamienienie Cię w atomowy pył.|'
foo.split('|')[1][2:]
'Dyspergator: "Pulvis es et in pulverem revertis" Raz na dwie walki i tylko raz w walce pozwala na uniknięcie następnego ataku przeciwnika poprzez chwilowe zamienienie Cię w atomowy pył.'