LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1036|回复: 3

替换文本中的某些字串

[复制链接]
发表于 2008-9-26 14:26:48 | 显示全部楼层 |阅读模式
htm文件中多个这样的字串:

href="[color="Red"]../03df0-03df5/05.pdf"
href="[color="Red"]../03e01-03e50/01.pdf"
href="[color="Red"]../avede-sdfed/00.pdf"

如何用script将

[color="Red"]../03df0-03df5/ 替换为 ../
[color="Red"]../03e01-03e50/ 替换为 ../
[color="Red"]../avede-sdfed/ 替换为 ../

或者说, 如何直接删掉 [color="Red"].. 后的12字符?

谢谢
发表于 2008-9-29 17:25:57 | 显示全部楼层
建议先看一下abs guide的Regular Expression章节. 花不了多少时间.
回复 支持 反对

使用道具 举报

发表于 2008-9-29 21:45:51 | 显示全部楼层
life is short - you need Python!

one stupid, but relative simple example
  1. import re
  2. a = 'href="../03df0-03df5/05.pdf"'
  3. b = '/'
  4. print re.sub(b+re.split(b, a)[1], '', a)
复制代码

input
href="../03df0-03df5/05.pdf"

output
href="../05.pdf"

to search and replace all <a> tag from *.html, you need beautifulsoup for extra help.
soup = BeautifulSoup.findAll('a'), and then apply the regex rules on those found entries within a loop.
回复 支持 反对

使用道具 举报

发表于 2008-9-30 01:32:43 | 显示全部楼层

  1. import re

  2. from BeautifulSoup import BeautifulSoup

  3. page = '''
  4. <html>
  5. <head>
  6. <title>
  7. </title>
  8. </head>
  9. <body>
  10. <h1>
  11. head level one
  12. </h1>
  13. <div id="atagholder">
  14.     <a href="../03df0-03df5/05.pdf">pdf one</a>
  15.     <a href="../03e01-03e50/01.pdf">pdf one</a>
  16.     <a href="../avede-sdfed/00.pdf">pdf one</a>
  17. </div>
  18. </body>
  19. </html>
  20. '''
  21. print page
  22. soup = BeautifulSoup(page)
  23. node = soup.findAll('a')
  24. for x in node:
  25.     x['href'] = '../'+re.split('"', re.split(sep, unicode(x))[2])[0]
  26. print soup
复制代码


  1. INPUT
  2. <html>
  3. <head>
  4. <title>
  5. </title>
  6. </head>
  7. <body>
  8. <h1>
  9. head level one
  10. </h1>
  11. <div id="atagholder">
  12.     <a href="../03df0-03df5/05.pdf">pdf one</a>
  13.     <a href="../03e01-03e50/01.pdf">pdf one</a>
  14.     <a href="../avede-sdfed/00.pdf">pdf one</a>
  15. </div>
  16. </body>
  17. </html>

  18. OUTPUT
  19. <html>
  20. <head>
  21. <title>
  22. </title>
  23. </head>
  24. <body>
  25. <h1>
  26. head level one
  27. </h1>
  28. <div id="atagholder">
  29. <a href="../05.pdf">pdf one</a>
  30. <a href="../01.pdf">pdf one</a>
  31. <a href="../00.pdf">pdf one</a>
  32. </div>
  33. </body>
  34. </html
复制代码
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表