返回文件中两个字符串之间的所有实例[Python3]

2024-06-01 08:39:50 发布

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

我要做的是打开一个文件,然后找到“[\x06I””和“\x06;”的每个实例,然后返回两者之间的任何内容。你知道吗

由于这不是一个标准的文本文件(它是来自RPG maker的地图数据),readline()对于我来说不起作用,因为该文件的格式根本不是我想要的数据总是整齐地放在一行中。你知道吗

我现在要做的是用read()将文件加载到一个列表中,然后从一开始就删除字符,直到找到字符串“[\x06I”。然后我向前扫描以找到“\x06;”,将它们之间的内容存储为字符串,将所述字符串附加到列表中,然后在找到的分号后的字符处继续。你知道吗

它奏效了,我最终得到了我想要的东西,但我觉得这是最糟糕的方式。有没有更有效的方法?你知道吗

我的相关代码:

while eofget == 0:

    savor = 0
    while savor == 0 or eofget == 0:
        if line[0:4] == '[\x06I"':
            x = 4
            spork = 0
            while spork == 0:
                x += 1
                if line[x] == '\x06':
                    if line[x+1] == ';':
                        spork = x
                        savor = line[5:spork] + "\n"
                        line = line[x+1:]
                        linefinal[lineinc] = savor
                        lineinc += 1
                elif line[x:x+7] == '@widthi':
                    print("eof reached")
                    spork = 1
                    eofget = 1
                    savor = 0
        elif line[x:x+7] == '@widthi':
            print("finished map " + mapname)
            eofget = 1
            savor = 0
            break
        else:
            line = line[1:]

你可以忽略变量名。当我做这种一次性的事情时,我首先想到的就是事情。是的,我知道其中有一些东西没有任何意义,但我正在保存清理,以备我完成代码时使用。你知道吗

当eofget被翻转时,这个子程序终止并加载下一个映射。然后重复。“@widthi”检查基本上是为了节省时间,因为它存在于每个地图中,并指示地图数据的开始,也就是我不关心的数据。你知道吗


Tags: 文件数据字符串内容列表ifline地图
2条回答

我会使用split():

fulltext = 'adsfasgaseg[\x06I"thisiswhatyouneed\x06;sdfaesgaegegaadsf[\x06I"this is the second what you need \x06;asdfeagaeef'

parts = fulltext.split('[\x06I"')        # split by first label
results = []
for part in parts:                       
   if '\x06;' in part:                   # if second label exists in part
      results.append(part.split('\x06;')[0])  # get the part until the second label

print results

我觉得这是使用正则表达式的自然情况。使用^{}方法:

>>> s = 'testing[\x06I"text in between 1\x06;filler text[\x06I"text in between 2\x06;more filler[\x06I"text in between \n with some line breaks \n included in the text\x06;ending'

>>> import re
>>> p = re.compile('\[\x06I"(.+?)\x06;', re.DOTALL)
>>> print(p.findall(s))
['text in between 1', 'text in between 2', 'text in between \n with some line breaks \n included in the text']

正则表达式字符串'\[\x06I"(.+?)\x06;'可以解释为:

Match as little as possible (denoted by ?) of an undetermined number of unspecified characters (denoted by .+) surrounded by '[\x06I"' and '\x06;', and only return the enclosed text (denoted by the parentheses around .+?)

在编译中添加^{}也会使.?匹配换行符,从而可以捕获多行文本。你知道吗

相关问题 更多 >