You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解析特定控制台输出并生成CSV文件?

问题描述

需将以下控制台输出转换为CSV文件:

ID,FLAG,ADDRESS,MAC-ADDRESS,HOST-NAME,SERVER,STATUS,LAST-SEEN
0   10.0.0.11     00:1D:72:29:F2:4F                lan      waiting  never
;;; test comment
1   10.0.0.19     00:13:21:15:D4:00                lan      waiting  never
2   10.0.0.10     00:60:6E:05:0C:E0                lan      waiting  never
3 D 10.0.1.199    24:E9:B3:20:FA:C7  home          server1  bound    4h54m52s
4 D 100.64.1.197  E6:17:AE:21:EA:00  Suzana-s-A51  dhcp1    bound    2h16m45s

已实现行拆分,但正则表达式无法正确处理制表符与空格的混合分隔,寻求解决方向。当前使用代码如下:

import csv
import re

# Open the input file in read-only mode
with open('output.txt', 'r') as input_file:
    # Open the output file in write-only mode
    with open('output.csv', 'w') as output_file:
        # Create a CSV writer that will write to the output file
        writer = csv.writer(output_file)

        # Read the first line of the input file (the header)
        # and write it to the output file as a single value
        # (i.e. do not split it on commas)
        header = input_file.readline()
        writer.writerow([header.strip()])

        # Iterate over the remaining lines of the input file
        for line in input_file:
            # Ignore lines that start with ";;;" (these are comments)
            if line.startswith(';;;'):
                continue

            # Split the line on newlines
            values = line.split('\n')

            line = re.sub(r'[\t ]+', ',', line)

            # Iterate over the resulting values
            for i, value in enumerate(values):
                # If the value contains a comma, split it on commas
                # and assign the resulting values to the `values` list
                if ',' in value:
                    values[i:i+1] = value.split(',')

            # Write the values to the output file
            writer.writerow(values)
解决方向
  • 用默认split()方法处理空白分隔:Python中str.split()不带参数时,会自动将任意数量的空白字符(空格、制表符等)视为分隔符,同时忽略行首尾空白,刚好适配这种混合空白分隔的场景,无需正则替换。
  • 修正表头处理逻辑:原代码将表头整行作为单个单元格写入CSV,正确做法是按逗号拆分表头后再写入,保证CSV列对应正确。
  • 简化行处理流程:去掉冗余的换行拆分、正则替换等步骤,直接对每一行做处理:跳过注释/空行→去除首尾空白→分割字段→写入CSV。
优化后的代码示例
import csv

with open('output.txt', 'r') as input_file, open('output.csv', 'w', newline='') as output_file:
    writer = csv.writer(output_file)
    # 处理表头:按逗号拆分
    header = input_file.readline().strip()
    writer.writerow(header.split(','))
    
    for line in input_file:
        line = line.strip()
        # 跳过注释行和空行
        if not line or line.startswith(';;;'):
            continue
        # 按任意空白分割字段
        fields = line.split()
        writer.writerow(fields)

内容的提问来源于stack exchange,提问作者Aleksa Markovic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 05:25:17