python - Python 中的文件操作

标签 python

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

注意:这两个词是固定的。例如:如果我的代码是这样的

'const int variablename=1'

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

s='const int variablename = 1'

k=s[s.find('int')+4:s.find('=')]

print k

最佳答案

如果文件适合内存,您可以通过单个正则表达式调用获得它:

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 = re.compile(
r"""(?x)
(?<=    # Assert that the text before the current location is:
 \b     # word boundary
 int    # "int"
 \s     # whitespace
)       # End of lookbehind
[^=\s]*   # Match any number of characters except = or space
(?=     # Assert that the following text is:
 \s*    # optional whitespace
 =      # "="
)       # end of lookahead""")

关于python - Python 中的文件操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6978770/

相关文章:

python - 传递关键字参数

Python + Mac 浏览器 : Error - 'chromedriver' executable needs to be in PATH

Python 在找到特定行后读取行

python - Selenium:FirefoxProfile 异常无法加载配置文件

python - 当我从 Django 网站使用 PyVirtualDisplay 运行 Selenium 时,为什么会出现 gnome 权限错误?

python - 自定义转换器和 GridSearch - 管道中的 ValueError

python - Setuptools 包发现

python - 从 Python 调用 CAPL 函数

python - PyGPU 信息/文档

python异步发布请求