【问题标题】:Regex replacement line by line in Python 3在 Python 3 中逐行替换正则表达式
【发布时间】: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


【解决方案1】:
lines = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!-- Page 1 -->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0" y="0" width="1198" height="1576" viewBox="0 0 1198 1576" version="1.1" style="display: block;margin-left: auto;margin-right: auto;">
<path d="M0,0 L0,1576 L1198,1576 L1198,0 Z " fill="#FFFFFF" stroke="none"/>
<image preserveAspectRatio="none" x="0" y="0" width="1199" height="1577" xlink:href="https://cdn-assets.somewhere.com/f929e7b4404d3e48918cdc0ecd4efbc9fa91dab5_2734/9c237c7e35efe88878f9e5f7a3555f7a379ed9ee9d95b491b6d0003fd80afc6b/9c68a28d6b5161f7e975a163ff093a81172916e23c778068c6bfefcfab195154.jpg?q=80"/>
<g fill="#112449">
<use xlink:href="#f0_2" transform="matrix(19.1,0,0,19.1,885.3,204.3)"/>
<use xlink:href="#f0_o" transform="matrix(19.1,0,0,19.1,910,204.3)"/>
<use xlink:href="#f0_t" transform="matrix(19.1,0,0,19.1,930.3,204.3)"/>
<use xlink:href="#f0_f" transform="matrix(19.1,0,0,19.1,949.6,204.3)"/>"""

import re

newlines = []
for line in lines.split('\n'):
    myregex = re.compile(r"(?:xlink:href\=\")(.*)(?:\?q=80\"\/\>)")
    result = myregex.search(line)

    if result:
        print(result)
        #If a match is found, replace the text in the line          
        origfullimgfilename = result.group(1)
        replfullimgfilename='page-##-img1.jpg'
        line = re.sub(origfullimgfilename, replfullimgfilename, line)  

    newlines.append(line)

print( '\n'.join(newlines) )

【讨论】:

  • 看起来它会起作用,但我想在一个 svg 文件中“就地”执行它......无论该行是否匹配,该代码是否会打印出整个文件?
  • 我找到的唯一解决方案是循环遍历enumerate(line_list),然后line_list[i] = re.sub()...(re.sub 返回字符串的副本),你想做一个 in-出于性能/内存原因更换?
  • 不是真的,只是为了让它更整洁。不过谢谢,我会尝试以这种方式写入一个单独的文件。谢谢
  • 好的,但是当我将正则表达式更改为 myregex = re.compile("(?:xlink:href\=\")(.*?q=80)") 它没有t ...
  • (?:xlink:href\=\")([^\"]*.jpg)? :我添加了.jpg,因为它也匹配&lt;use xlink:href="#f0_f"...我不知道您是否要包含?q= 部分
猜你喜欢
  • 2015-01-06
  • 1970-01-01
  • 2013-06-13
  • 1970-01-01
  • 1970-01-01
  • 2012-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多