免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2119 | 回复: 3
打印 上一主题 下一主题

大侠帮忙:一个模式匹配的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-03-21 23:51 |只看该作者 |倒序浏览
a ='<p>吖<span lang=EN-US> ā [</span>吖嗪<span lang=EN-US>] (ā</span>q<span
lang=EN-US>í</span>n<span lang=EN-US>) '
a是类似以上的字符串,我要把其中 [</span>吖嗪<span lang=EN-US>] 变成 [吖嗪]
我的思路是:找出a中所有的[....]生成一个列表,然后去掉里面的html标记得到一个列表,然后将a中所有的[...]
替换成没有html的列表,得到的两个列表都没问题,就是替换中出来毛病,请高手指点!

  1. #将所有[]里面的内容读到s1里面

  2. s1 = re.compile('\[[^\]]*\]',re.S|re.M).findall(a)
  3. dd = []
  4. for  x in s1:
  5.     x1 = re.compile('\<[^\>]*\>',re.S|re.M).sub('',x)  #将[]内的html标记(<>里面的内容)去掉
  6.     dd.append(x1)
复制代码


这样得到了两个列表,其中s1是含有html标记的,dd是没有html标记的,我想把a里面所有的x1替换成dd

  1. ff = re.sub(s1[0],dd[0],a)
  2. while i<len(s1):
  3.     ff = re.sub(s1[i],dd[i],ff)
  4.     print s1[i]
  5.     print dd[i]
  6.     i +=1
  7. print ff
复制代码

这种做法循环多次,不能达到目的,不知道这里该怎么替换?

论坛徽章:
0
2 [报告]
发表于 2006-03-22 09:47 |只看该作者
因为s1, 和 dd 都是解析出来后的结果,那么它们应该不用再解析了。可以简单的使用replace


  1. for i in range(len(s1)):
  2.     a = a.replace(s1[i], dd[i])
  3. print a
复制代码


或使用re.sub也可以,但要使用re.escape将特殊字符作一个处理,这样不会认为是正则表达式规则了,如:


  1. for i in range(len(s1)):
  2.     a = re.sub(re.escape(s1[i]), dd[i], a)
  3. print a
复制代码


还可以在更简化,一次就做完:


  1. #coding=cp936
  2. import re

  3. a ='<p>吖<span lang=EN-US> ā [</span>吖嗪<span lang=EN-US>] (ā</span>q<span lang=EN-US>í</span>n<span lang=EN-US>) '

  4. def do_sub(m):
  5.     return re.sub(r'<.*?>', '', m.group())
  6. a = re.sub(r'\[.*?\]', do_sub, a)
  7. print a
复制代码


只不过你的要求好象有问题。象[</span>这个</span>是与前一个<span>对应的。你把它去掉的话,就对应不上了。后面那个也是。

另外可以通过 .*? 这种方式来处理,使用r可以简化字符串的书写。下面是在python文档中的一段话,关于?的,可以参考一下:

*?, +?, ??

The "*", "+", and "?" qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn't desired; if the RE <.*> is matched against '<H1>title</H1>', it will match the entire string, and not just '<H1>'. Adding "?" after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using .*? in the previous expression will match only '<H1>'.

论坛徽章:
0
3 [报告]
发表于 2006-03-22 10:54 |只看该作者
恩,先消化一下!

论坛徽章:
0
4 [报告]
发表于 2006-03-22 11:06 |只看该作者
严重感谢limodou大侠,特别是那个.*?省了我不少事,谢谢!
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP