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

如何用Python/PowerShell移除竖线分隔文件列外层双引号(保留JSON内引号)

解决方案:移除Pipe分隔文件的列外层双引号(保留JSON内引号)

Python 实现

使用Python内置的csv模块是最可靠的方案,它能自动识别带引号的字段,移除外层引号的同时保留字段内部的引号(如JSON结构中的引号):

import csv

input_file = "input.txt"
output_file = "output.txt"

with open(input_file, 'r', encoding='utf-8') as infile, open(output_file, 'w', encoding='utf-8', newline='') as outfile:
    # 指定分隔符为竖线,引号字符为双引号
    reader = csv.reader(infile, delimiter='|', quotechar='"')
    writer = csv.writer(outfile, delimiter='|', quoting=csv.QUOTE_NONE)
    
    for row in reader:
        writer.writerow(row)

逻辑说明

  • csv.reader会自动解析每个被双引号包裹的字段,剥离外层引号,同时完整保留字段内部的内容(包括JSON里的双引号)。
  • csv.writer设置quoting=csv.QUOTE_NONE,确保输出时不会重新给字段添加引号,直接用竖线分隔。

PowerShell 实现

提供两种处理方式,按需选择:

方式1:使用Import-Csv/Export-Csv(适合结构化数据)

$inputPath = "input.txt"
$outputPath = "output.txt"

# 导入文件,指定分隔符和引号规则
$csvData = Import-Csv -Path $inputPath -Delimiter '|' -QuoteChar '"'

# 导出时禁用引号,用竖线分隔
$csvData | Export-Csv -Path $outputPath -Delimiter '|' -NoTypeInformation -UseQuotes Never

方式2:逐行正则替换(适合大文件,低内存占用)

$inputPath = "input.txt"
$outputPath = "output.txt"

Get-Content -Path $inputPath | ForEach-Object {
    # 匹配并移除字段外层的双引号,保留内部引号
    $_ -replace '(?<=^|\|)"([^"\\]*(?:\\.[^"\\]*)*)"(?=\||$)', '$1'
} | Set-Content -Path $outputPath -Encoding utf8

逻辑说明

  • 方式1利用PowerShell的CSV处理能力,自动识别带引号的字段,导出时禁用引号输出。
  • 方式2的正则表达式精准匹配被竖线分隔的字段外层引号,仅移除字段首尾的引号,不会影响内部JSON结构中的引号。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 13:55:18