如何在python中读取ascii格式的表

2024-04-29 19:52:35 发布

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

我有以下格式的一些配置数据。在python中解析这些数据的最佳方法是什么?我检查了csv模块和简要的this模块。不知道怎么用。现有的解析器是用perl进行黑客攻击的。在

|------------+-----------------+--------|
| ColHead1   | Col_______Head2 | CH3    |
|------------+-----------------+--------|
| abcdefg000 | *               | somev1 |
| abcdefg001 | *               | somev2 |
| abcdefg002 | *               |        |
| abcdefg003 | *               |        |
| abcdefg004 | *               |        |
| abcdefg005 | *               |        |
| abcdefg006 | *               |        |
| abcdefg007 | *               |        |
| abcdefg008 | *               |        |
| abcdefg009 | *               |        |
| abcdefg010 | *               |        |
|------------+-----------------+--------|


Tags: 模块csv数据方法解析器格式colthis
2条回答

你可以试试这样的方法:

def parse(ascii_table):
    header = []
    data = []
    for line in filter(None, ascii_table.split('\n')):
        if '-+-' in line:
            continue
        if not header:
            header = filter(lambda x: x!='|', line.split())
            continue
        data.append(['']*len(header))
        splitted_line = filter(lambda x: x!='|', line.split())
        for i in range(len(splitted_line)):
            data[-1][i]=splitted_line[i]
    return header, data

这是另一种(类似的)方法 如果它在文件中:

with open(filepath) as f:
    for line in f:
        if '-+-' in line or 'Head' in line:
            continue
        # strip '|' off the ends then split on '|'
        c1, c2, c3 =  line.strip('|').split('|')
        print 'Col1: {}\tCol2: {}\tCol3: {}'.format(c1,c2,c3)

或字符串变量:

^{pr2}$

相关问题 更多 >