在html的解析中
<div>
<h3>
<small style="text-align:left;color:gray;">05/23 13:58頃</small>
<small>苫小牧市</small><br>
(支援)苫小牧市新富町1丁目
</h3> 在python中,我必须以支援的形式从小括号'( )‘中获取数据。当我试图通过命令获取数据时
text = div.h3.findAll(text=True, recursive=False)[2].strip()我得到了
u'\uff08\u652f\u63f4\uff09\u82eb\u5c0f\u7267\u5e02\u65b0\u5bcc\u753a1\u4e01\u76ee'这是'(支援)苫小牧市新富町1丁目'的unicode数据,所以我无法以'支援'的形式从小括号中获取数据。
发布于 2018-05-23 14:17:34
BeautifulSoup不会帮助您解析子字符串。您可以使用Python的string方法来处理这个问题,也可以使用正则表达式。
这里的开始和结束括号是U+FF08和U+FF09完全宽度括号,您可以在这些圆括号上对字符串进行分区:
text.partition(u'\uff08')[-1].partition(u'\uff09')[0]或者您可以使用一个正则表达式,在两个这样的代码点之间获取所有文本:
re.search(ur'\uff08([^\uff09]*)\uff09', text).group(1)它们都适用于您的示例字符串:
>>> print text.partition(u'\uff08')[-1].partition(u'\uff09')[0]
支援
>>> import re
>>> print re.search(ur'\uff08([^\uff09]*)\uff09', text).group(1)
支援区别在于它们如何处理没有一个或两个括号的字符串;在这些情况下,re.search()将返回None,然后您将得到一个AttributeError,用于尝试在该对象上使用.group,而str.partition()将生成一个空字符串或一个部分字符串:
>>> text = u'no parentheses'
>>> text.partition(u'\uff08')[-1].partition(u'\uff09')[0]
u''
>>> text = u'\uff08open parentheses'
>>> text.partition(u'\uff08')[-1].partition(u'\uff09')[0]
u'open parentheses'
>>> text = u'close parentheses\uff09'
>>> text.partition(u'\uff08')[-1].partition(u'\uff09')[0]
u''选择最适合你需要的方法。
https://stackoverflow.com/questions/50490445
复制相似问题