Skip to main content
 首页 » 编程设计

python之Python 中的文件操作

2025年05月04日20shanyou

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

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

'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""")