【问题标题】:Python Regular Expressions Excluding TagsPython 正则表达式不包括标签
【发布时间】:2014-06-19 12:50:35
【问题描述】:

我写了一个脚本,发布在下面,它基本上会进入纯文本字典网站并搜索输入的单词并检索定义。唯一的问题是它也返回了结束段落标签,我已经搞砸了很多年了。

#!/usr/bin/python
import urllib2
import re
import sys


word = 'Xylophone'
page = urllib2.urlopen('http://www.mso.anu.edu.au/~ralph/OPTED/v003/wb1913_'+word[0].lower()+'.html')
html = page.read()

match = re.search(r'<P><B>'+word+'</B>.............(.*)', html)

if match: 
    print match.group(1)
else: print 'not found'

这将返回带有标签的定义。这里忽略标签的正确正则表达式语法是什么?

【问题讨论】:

标签: python html regex web-scraping html-parsing


【解决方案1】:

先决条件:阅读RegEx match open tags except XHTML self-contained tags著名话题。

由于您要解析的是一个 html 页面,因此我会使用专门为此设计的工具 - HTML parser

例如BeautifulSoup:

import urllib2
from bs4 import BeautifulSoup

word = 'Xylophone'
page = urllib2.urlopen('http://www.mso.anu.edu.au/~ralph/OPTED/v003/wb1913_'+word[0].lower()+'.html')
soup = BeautifulSoup(page)

print soup.find('b', text=word).parent.text

打印:

木琴 (n.) 一种常见于俄罗斯人、波兰人和 鞑靼人,由一系列木条或玻璃条组成,有刻度 长到音阶,靠在稻草带上,敲击 用两把小锤子。在德国称为 strohfiedel,或稻草 小提琴。

【讨论】:

  • 同意 alecxe - 这是更清洁的方式......但只是添加 (?

    ) 使其无法捕获......意味着它会检查它但不会返回它..

  • 如何将 (?

    ) 添加到上述代码中?我只是用这种方式不断出错

  • @user3366103 代码无需任何更改即可工作 - 它获取关键字的定义。
  • 是的,alecxe 发布的代码有效,但是我如何将 (?

    ) 添加到原始代码中,因为这看起来更易读?

  • @user3366103 当然,你需要先安装它:pip install beautifulsoup4
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-15
  • 2016-09-29
  • 2015-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-15
相关资源
最近更新 更多