Python正则表达式,不包括标记

2024-03-29 11:05:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经写了一个脚本,张贴在下面,它基本上到纯文本词典网站,搜索输入的单词和检索的定义。唯一的问题是它返回结束段标签以及,我已经乱搞了好几年了。你知道吗

#!/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'

这将返回带有标记的定义。忽略标记的正确regex语法是什么?你知道吗


Tags: 标记文本importre脚本定义网站html
1条回答
网友
1楼 · 发布于 2024-03-29 11:05:11

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

因为您正在解析的是一个html页面,所以我会使用一个专门的工具-an HTML parser。你知道吗

例如,^{}

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

印刷品:

Xylophone (n.) An instrument common among the Russians, Poles, and Tartars, consisting of a series of strips of wood or glass graduated in length to the musical scale, resting on belts of straw, and struck with two small hammers. Called in Germany strohfiedel, or straw fiddle.

相关问题 更多 >