【问题标题】:regex findall in beautifulsoup -python 3beautifulsoup -python 3 中的正则表达式 findall
【发布时间】:2017-01-05 15:53:03
【问题描述】:

我需要获取标签 ix:nonfraction 下所有字段的名称和值以及上下文引用,如下所示:

<ix:nonfraction name="uk-gaap:TangibleFixedAssets" contextref="FY1.END" unitref="GBP" xmlns:uk-gaap="http://www.xbrl.org/uk/gaap/core/2009-09-01" decimals="0" format="ixt:numcommadot">238,011</ix:nonfraction>

所需的输出为:

TangibleFixedAssets, FY1.end, 238,011

正则表达式必须搜索的字符串包含许多这样的标签,那么是否有办法将所有 3 个输出保持连接(或在列表的同一索引内)?

【问题讨论】:

  • 试试这个 \([\w\,]+)\.使用 g 全局修饰符

标签: regex python-3.x parsing beautifulsoup findall


【解决方案1】:
import bs4
html = '''<ix:nonfraction name="uk-gaap:TangibleFixedAssets" contextref="FY1.END" unitref="GBP" xmlns:uk-gaap="http://www.xbrl.org/uk/gaap/core/2009-09-01" decimals="0" format="ixt:numcommadot">238,011</ix:nonfraction>'''

soup = bs4.BeautifulSoup(html, 'lxml')

ixs = soup.find_all('ix:nonfraction')
for ix in ixs:
    name = ix['name'].split(':')[-1]
    contextref = ix['contextref']
    text = ix.text
    output = [name, contextref, text]
    print(output)

出来:

['TangibleFixedAssets', 'FY1.END', '238,011']

【讨论】:

    猜你喜欢
    • 2015-08-13
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    相关资源
    最近更新 更多