2013-04-03 65 views
1

我有一些html文件,其中包含指向文件名包含空格的文件的链接。例如,替换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似乎由线工作线)。

任何援助将不胜感激。

回答

3

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

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