2013-04-03 52 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))