Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用shell或批处理命令行将Python表格转换为CSV_Python_Csv_Prettytable - Fatal编程技术网

使用shell或批处理命令行将Python表格转换为CSV

使用shell或批处理命令行将Python表格转换为CSV,python,csv,prettytable,Python,Csv,Prettytable,将Python Pretty表的输出转换为语法上可用的格式(如CSV)的简单方法是什么 输出如下所示: C:\test>nova列表 spu+--------------------------------------+--------+--------+------------+-------------+-----------------------------------+ | ID | Name |

将Python Pretty表的输出转换为语法上可用的格式(如CSV)的简单方法是什么

输出如下所示:

C:\test>nova列表

    spu+--------------------------------------+--------+--------+------------+-------------+-----------------------------------+
     | ID                                   | Name   | Status | Task State | Power State | Networks                          |
     +--------------------------------------+--------+--------+------------+-------------+-----------------------------------+
     | 6bca09f8-a320-44d4-a11f-647dcec0aaa1 | tester | ACTIVE | -          |  Running     | OpenStack-net=10.0.0.1, 10.0.0.3 |
     +--------------------------------------+--------+--------+------------+-------------+-----------------------------------+

也许这会让你接近:

nova list | grep -v '\-\-\-\-' | sed 's/^[^|]\+|//g' | sed 's/|\(.\)/,\1/g' | tr '|' '\n'
这将剥去这些线 拆下引线| 将除最后一个之外的所有|替换为,
用\n

替换最后一个|这是一个非常难看的衬里

import csv

s = """\
  spu+--------------------------------------+--------+--------+------------+-------------+-----------------------------------+
     | ID                                   | Name   | Status | Task State | Power State | Networks                          |
     +--------------------------------------+--------+--------+------------+-------------+-----------------------------------+
     | 6bca09f8-a320-44d4-a11f-647dcec0aaa1 | tester | ACTIVE | -          |  Running     | OpenStack-net=10.0.0.1, 10.0.0.3 |
     +--------------------------------------+--------+--------+------------+-------------+-----------------------------------+"""

result = [tuple(filter(None, map(str.strip, splitline))) for line in s.splitlines() for splitline in [line.split("|")] if len(splitline) > 1]

with open('output.csv', 'wb') as outcsv:
    writer = csv.writer(outcsv)
    writer.writerows(result)
我可以把它打开一点,让它更漂亮:

splitlines = s.splitlines()
splitdata = line.split("|")
splitdata = filter(lambda line: len(line) > 1, data)
# toss the lines that don't have any data in them -- pure separator lines
header, *data = [[field.strip() for field in line if field.strip()] for line in splitdata]

result = [header] + data
# I'm really just separating these, then re-joining them, but sometimes having
# the headers separately is an important thing!
或者可能更有用:

result = []

for line in s.splitlines():
    splitdata = line.split("|")
    if len(splitdata) == 1:
        continue  # skip lines with no separators
    linedata = []
    for field in splitdata:
        field = field.strip()
        if field:
            linedata.append(field)
    result.append(linedata)

下面是一个使用正则表达式的解决方案。它也适用于任意数量的列(列的数量通过计算第一个输入行中加号的数量来确定)


@AdamSmith的答案提供了一种解析原始表字符串的好方法。下面是一些将其转换为通用函数的补充(我选择不使用
csv
模块,因此没有其他依赖项)


谢谢你调查,但我想应该有个地方可以逃走?C:\test>nova list | grep-V'----sed's/^[^ |]\+\124;//g'| sed's/|(.)/,\1/g'| tr'.'''\n'grep:unrecognized option'----用法:grep[option]。。。模式[文件]。。。请尝试“grep--help”以获取更多信息。这并不是在抱怨v,它不喜欢破折号:grep:unrecognized option'----'这不是由脚本生成的,它是由OpenStack CLI输出生成的,它们使用的是漂亮的表我现在可以评论了!谢谢。文件名不随此显示method@DhairyTripathi可能是因为len(data)==0吗?是的,是我的错。
input_string = """spu+--------------------------------------+--------+--------+------------+-------------+-----------------------------------+
     | ID                                   | Name   | Status | Task State | Power State | Networks                          |
     +--------------------------------------+--------+--------+------------+-------------+-----------------------------------+
     | 6bca09f8-a320-44d4-a11f-647dcec0aaa1 | tester | ACTIVE | -          |  Running     | OpenStack-net=10.0.0.1, 10.0.0.3 |
     +--------------------------------------+--------+--------+------------+-------------+-----------------------------------+"""

import re, csv, sys
def pretty_table_to_tuples(input_str):
    lines = input_str.split("\n")
    num_columns = len(re.findall("\+", lines[0])) - 1
    line_regex = r"\|" + (r" +(.*?) +\|"*num_columns)
    for line in lines:
        m = re.match(line_regex, line.strip())
        if m:
            yield m.groups()

w = csv.writer(sys.stdout)
w.writerows(pretty_table_to_tuples(input_string))
def ptable_to_csv(table, filename, headers=True):
    """Save PrettyTable results to a CSV file.

    Adapted from @AdamSmith https://stackoverflow.com/questions/32128226

    :param PrettyTable table: Table object to get data from.
    :param str filename: Filepath for the output CSV.
    :param bool headers: Whether to include the header row in the CSV.
    :return: None
    """
    raw = table.get_string()
    data = [tuple(filter(None, map(str.strip, splitline)))
            for line in raw.splitlines()
            for splitline in [line.split('|')] if len(splitline) > 1]
    if table.title is not None:
        data = data[1:]
    if not headers:
        data = data[1:]
    with open(filename, 'w') as f:
        for d in data:
            f.write('{}\n'.format(','.join(d)))