python - 返回文件中两个字符串之间的任何内容的每个实例 [Python 3]

标签 python string list

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

因为这不是一个标准的文本文件(它是来自 RPG maker 的 map 数据)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 被翻转时,此子例程终止并加载下一张 map 。然后重复。 “@widthi”检查基本上是为了节省时间,因为它出现在每张 map 中并指示 map 数据的开始,也就是我不关心的数据。

最佳答案

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

>>> 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 .+?)

添加re.DOTALL在编译中使 .? 也匹配换行符,允许捕获多行文本。

关于python - 返回文件中两个字符串之间的任何内容的每个实例 [Python 3],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30367426/

相关文章:

python - 如何使用递归函数Python查找列表子集的总和

Python:根据季度数计算月份、季度详细信息

python - 使用 pip 安装factory_boy 时遇到问题

string - 将两个字符串连接在一起

c - C 中使用分隔符分割字符串

r - 匹配多个字符串并加入

list - Lua 函数在源代码中使用 "self"但没有元方法允许使用它们

python - 在redis中存储和获取django模型对象

python - Homebrew brew doctor 警告关于/Library/Frameworks/Python.framework,即使安装了 brew 的 Python

list - 如何在汇合中继续编号列表?