如何创建动态选项卡

2024-06-15 08:55:58 发布

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

我正在使用以下代码创建一个表,该代码基于XML中提供的输入,运行良好,但我想转换为代码来动态创建表,这意味着如果我添加更多的列,代码应自动调整。.目前我已硬编码表将包含四列。.请建议哪些更改需要为实现这一点而对代码进行操作

输入XML:-在

<Fixes>
CR           FA      CL                    TITLE

409452      WLAN    656885        Age out RSSI values from buffer in Beacon miss scenario  
12345,45678  BT     54567,34567   Test
379104       BT     656928        CR379104: BT doesn’t work that Riva neither sends HCI Evt for HID ACL data nor response to HCI_INQUIRY after entering into pseudo sniff subrating mode.
</Fixes>

Python代码

^{pr2}$

Tags: 代码编码agetitleclxmlout建议
2条回答

它看起来不像一个XML文件,它看起来像一对标记中以制表符分隔的CSV文档。在

我建议查看csv模块来解析输入文件,然后使用一个类似jinja2的模板引擎来编写HTML生成。在

本质上-读入csv,检查标题的长度(给出列数),然后将数据传递到模板中。在模板中,您将在csv结构上有一个循环来生成HTML。在

虽然我对提供这个有一些保留意见,因为你似乎不愿意亲自尝试,但这里有一个例子说明了一种方法可以做到这一切,希望至少你会倾向于努力学习,并可能从中学到一些东西,即使它是交给你的。。。在

with open('cr_fixes.xml') as file: # get some data to process
    xmlfile = file.read()

def CRlistToTable(CRlist):
    cols = CRlist[0] # first item is header-row of col names on the first line

    CRstrings = ['<table cellspacing="1" cellpadding="1" border="1">']
    # table header row
    CRstrings.append('  <tr>')
    for col in cols:
        CRstrings.append('    <th bgcolor="#67B0F9" scope="col">{}</th>'.format(col))
    CRstrings.append('  </tr>')

    # create a template for each table row
    TR_TEMPLATE = ['  <tr>']
    # 1st col of each row is CR and handled separately since it corresponds to a link
    TR_TEMPLATE.append(
        '    <td><a href="http://prism/CR/{{{}}}">{{{}}}</a></td>'.format(*[cols[0]]*2))
    for col in cols[1:]:
        TR_TEMPLATE.append('    <td>{{}}</td>'.format(col))
    TR_TEMPLATE.append('  </tr>')
    TR_TEMPLATE = '\n'.join(TR_TEMPLATE)

    # then apply the template to all the non-header rows of CRlist
    for items in CRlist[1:]:
        CRstrings.append(TR_TEMPLATE.format(CR=items[0], *items[1:]))
    CRstrings.append("</table>")

    return '\n'.join(CRstrings) + '\n'

FIXES_START_TAG, FIXES_END_TAG = '<Fixes>, </Fixes>'.replace(',', ' ').split()
CRsFixesStart = xmlfile.find(FIXES_START_TAG) + len(FIXES_START_TAG)
CRsFixesEnd = xmlfile.find(FIXES_END_TAG)
info = xmlfile[CRsFixesStart:CRsFixesEnd].strip().splitlines()

# first line of extracted info is a blank-separated list of column names
num_cols = len(info[0].split())

# split non-blank lines of info into list of columnar data
# assuming last col is the variable-length title, comprising reminder of line
CRlist = [line.split(None, num_cols-1) for line in info if line]

# convert list into html table
crInfo = CRlistToTable(CRlist)
print crInfo

输出:

^{pr2}$

enter image description here

相关问题 更多 >