【发布时间】:2019-01-12 19:06:20
【问题描述】:
我已经编写了一些代码来尝试执行以下操作
- 打开我之前在 Python 代码中检索到的 SVG 文件
- 在文件中查找特定的正则表达式 (r"(?:xlink:href\=\")(.*)(?:\?q=80\"/>)")
- 如果找到匹配项,请将文本替换为特定字符串,例如 https://regex101.com/r/IECsHu/1
- 然后从匹配的 url 中检索 JPG(参见上面的 regex101.com 链接)
但是,这不起作用并完全清除文件(因此它是 0 字节)
我想我一定很接近让这个工作,但还没有做到。任何指导将不胜感激
pagenumber=1
directory_in_str='/home/somewhere/somedir/'
pathlist = Path(directory_in_str).glob('**/*.svg')
for path in pathlist:
#because path is object not string
path_in_str = str(path)
print(path_in_str)
with open(path_in_str, 'r+') as f:
for line in f:
myregex = r"(?:xlink:href\=\")(.*)(?:\?q=80\"\/\>)"
result = myregex.search(line)
if result:
#If a match is found, replace the text in the line
origfullimgfilename = result
formattedpagenumber = '{:0>3}'.format(pagenumber)
replfullimgfilename='page-'+str(formattedpagenumber)+'-img1.jpg'
line = re.sub(origfullimgfilename, replfullimgfilename, line.rstrip())
#Then retrieve the file! (origfullimgfilename)
try:
urllib.request.urlretrieve(origfullimgfilename+"?q=100", replfullimgfilename)
except urllib.error.HTTPError as e:
print("HTTP Error: "+str(e.code)+" - SVG URL: "+str(origfullimgfilename)+" - aborting\n")
break
pagenumber += 1
【问题讨论】:
-
这不应该发生。发布整个程序和输入文件将有助于其他人检查它。
-
嗨@ben 哪一部分不应该发生?上面的代码作为独立运行,一旦 SVG 文件在目录中......我已经将它分成一个单独的 .py 文件,因为到目前为止一切正常。
-
检查什么是
result,使用我拥有的代码的修改版本:<_sre.SRE_Match object; span=(73, 305), match='xlink:href="https://cdn-assets.somewhere.com/f929>... 它不应该是:myregex = re.compile("(?:xlink:href\=\")(.*)(?:\?q=80\"\/\>)")? -
@xdze2 应该是'cdn-assets.somewhere.com/…'
标签: python regex svg replace inline