【问题标题】:Replace spaces in substrings in an HTML file替换 HTML 文件中子字符串中的空格
【发布时间】:2013-03-25 14:51:20
【问题描述】:

我有一些 html 文件,其中包含指向文件名包含空格的文件的链接。例如,

The rain in spain ... 
<a href="/path/filename with space.xls">Filename</a>
falls mainly on the plain.

<a href="/path/2nd filename with space.doc">2nd Filename</a>

文件中通常有多个这样的链接。我想仅替换文件名本身中的空格,但不要触摸文件中其他地方的空格。例如:

<a href="/path/filename_with_space.xls">Filename</a>

我尝试过使用 SED,但我似乎无法将替换隔离在 2 个正则表达式模式之间(sed 似乎逐行工作)。

任何帮助将不胜感激。

【问题讨论】:

    标签: html regex sed


    【解决方案1】:

    Do not use regex for this problem。使用 html 解析器。这是 Python 中的 BeautifulSoup 解决方案:

    from BeautifulSoup import BeautifulSoup
    
    with open('Path/to/file', 'r') as content_file:
        content = content_file.read()
    
    soup = BeautifulSoup(content)
    for a in soup.findAll('a')
      a['href'] = a['href'].replace(" ", "_")
    
    with open('Path/to/file.modified', 'w') as output_file:
        output_file.write(str(soup))
    

    【讨论】:

      猜你喜欢
      • 2018-09-19
      • 1970-01-01
      • 2020-12-19
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 1970-01-01
      • 2019-06-13
      相关资源
      最近更新 更多