gpt4 book ai didi

python - 无法从 python 3 中的输入文件中找到子字符串

转载 作者:太空宇宙 更新时间:2023-11-03 18:32:10 25 4
gpt4 key购买 nike

我正在尝试从输入文件中查找格式。但有时如果我使用 'r' 则找不到匹配项,有时还会出现 unicode 错误。

def extract_files(filename):
file = open(filename, 'r')
text = file.read()
files_match = re.findall('<Compile Include="src\asf\preprocessor\string.h">', text)
if not files_match:
sys.stderr.write('no match')
sys.exit()
for f in files_match:
print(f)

最佳答案

看起来您正试图在<Compile Include="之后拉动所有的弦。直到 "> 。我们可以做到这一点,但请注意,这可能会在边缘情况下崩溃!

import re

def extract_files(filename):
with open(filename,'r') as file:
text = file.read
matches = re.findall(r'(?<=<Compile Include=")[-.A-Za-z\\]+(?=")', text)
# finds all pathnames that contain ONLY lowercase or uppercase letters,
# a dash (-) or a dot (.), separated ONLY by a backslash (\)
# terminates as soon as it finds a double-quote ("), NOT WHEN IT FINDS A
# SINGLE QUOTE (')
if not matches:
sys.stderr.write("no match")
sys.exit()
for match in matches:
print(match)

关于python - 无法从 python 3 中的输入文件中找到子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22233979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com