无法从 unicode 中获取两个字符之间的数据



In parseing of 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'uff08u652fu63f4uff09u82ebu5c0fu7267u5e02u65b0u5bccu753a1u4e01u76ee'

它是'(支援)苫小牧市新富町1丁目'的 unicode 数据,所以我无法从小括号中获取数据作为'支援'

BeautifulSoup 不会帮助你解析出子字符串。您可以使用 Python 的字符串方法来处理此问题,也可以使用正则表达式。

这里的左括号和右括号是 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,然后您会收到尝试在该对象上使用.groupAttributeError,而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 parenthesesuff09'
>>> text.partition(u'uff08')[-1].partition(u'uff09')[0]
u''

选择最适合您需求的方法。

最新更新