Python中的文件操作

2024-04-25 17:44:56 发布

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

我有一段代码,它提取了一个介于两个字符串之间的字符串字符串。但是,此脚本只对一行执行此操作。我希望对完整文件执行此操作,并获取位于这两个单词之间的所有单词的列表。在

在注:两者文字是固定。用于如果我的代码是

'const int variablename=1'

然后我想要一个文件中位于'int''='之间的所有单词的列表。 以下是当前脚本:

^{pr2}$

Tags: 文件字符串代码脚本列表单词int文字
3条回答

如果文件可以轻松放入内存中,则可以通过一个regex调用获得:

import re
regex = re.compile(
r"""(?x)
(?<=    # Assert that the text before the current location is:
 \b     # word boundary
 int    # "int"
 \s     # whitespace
)       # End of lookbehind
[^=]*   # Match any number of characters except =
(?<!\s) # Assert that the previous character isn't whitespace.
(?=     # Assert that the following text is:
 \s*    # optional whitespace
 =      # "="
)       # end of lookahead""")
with open(filename) as fn:
    text = fn.read()
    matches = regex.findall(text)

如果int=之间只能有一个单词,那么regex就更简单了:

^{pr2}$
with open(filename) as fn:
    for row in fn:
        # do something with the row?

我会在整个文本中使用正则表达式(您也可以在一行上这样做)。这将打印“int”和“=”之间的字符串

import re

text = open('example.txt').read()
print re.findall('(?<=int\s).*?(?=\=)', text)

相关问题 更多 >

    热门问题