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

如何用Python和JavaScript消除TSV文件引号内的换行?

处理TSV文件中引号内换行的Python和JavaScript实现

现有包含多列的TSV文件,其中「Examples」列的引号内存在换行,导致格式异常。需要将引号内的所有示例语句合并到同一行的对应列中,保留其他列的结构。

实际输入的example.tsv内容:

ID   Data   Fruit   Examples
1   August   Apple   "I have an apple. (Ana) 
I give her an apple. (Tomas) 
There are apples (Lisa)"
2   July   Melon   "I have a melon. (Ana) 
I give him a melon. (Tomas) 
There are melons (Lisa)"
3   May   Lemon   "I have a lemon. (Ana) 
I give him a lemon. (Tomas) 
There are lemons (Lisa)"
...   

理想输出的example.tsv内容:

ID   Data   Fruit   Examples
1   August   Apple   "I have an apple. (Ana) I give her an apple. (Tomas) There are apples (Lisa)"
2   July   Melon   "I have a melon. (Ana) I give him a melon. (Tomas) There are melons (Lisa)"
3   May   Lemon   "I have a lemon. (Ana) I give him a lemon. (Tomas) There are lemons (Lisa)"

Python 实现

方法1:使用csv模块(推荐,边界场景处理更可靠)

TSV本质是制表符分隔的CSV文件,Python内置的csv模块可以自动识别带引号的字段,完美处理字段内的换行。读取后将目标字段内的换行替换为空格,再重新写入即可。

import csv

input_file = 'example.tsv'
output_file = 'formatted_example.tsv'

with open(input_file, 'r', encoding='utf-8') as infile, open(output_file, 'w', encoding='utf-8', newline='') as outfile:
    # 配置TSV读写器,指定分隔符为制表符
    reader = csv.DictReader(infile, delimiter='\t')
    writer = csv.DictWriter(outfile, fieldnames=reader.fieldnames, delimiter='\t', quoting=csv.QUOTE_NONNUMERIC)
    
    writer.writeheader()
    for row in reader:
        # 替换Examples字段内的换行与多余空格
        row['Examples'] = row['Examples'].replace('\n', ' ').replace('\r', '').strip()
        writer.writerow(row)

方法2:使用正则表达式

如果不想依赖csv模块,可以用正则精准匹配双引号内部的换行,避免误替换行与行之间的正常分隔换行。

import re

input_file = 'example.tsv'
output_file = 'formatted_example.tsv'

with open(input_file, 'r', encoding='utf-8') as file:
    content = file.read()

# 仅替换双引号内的换行,同时去除换行前后的多余空格
content_replaced = re.sub(r'(?<="[^"]*)\s*\n\s*(?=[^"]*")', ' ', content)

with open(output_file, 'w', encoding='utf-8') as file:
    file.write(content_replaced)

说明:你之前的正则会替换所有换行(包括行分隔符),导致所有内容合并成一行,这是无法得到正确结果的核心原因。上面的正则通过环视语法,仅定位双引号内部的换行进行替换。


JavaScript 实现(Node.js环境)

方法1:使用csv-parser和csv-writer库(推荐)

Node.js中可以借助第三方库处理TSV,同样能正确识别带引号的字段,避免手动处理的边界问题。

首先安装依赖:

npm install csv-parser csv-writer

编写处理代码:

const fs = require('fs');
const csv = require('csv-parser');
const createCsvWriter = require('csv-writer').createObjectCsvWriter;

const inputFile = 'example.tsv';
const outputFile = 'formatted_example.tsv';
const results = [];

// 读取并处理TSV内容
fs.createReadStream(inputFile, 'utf8')
  .pipe(csv({ separator: '\t' }))
  .on('data', (data) => {
    // 替换Examples字段内的换行
    data.Examples = data.Examples.replace(/[\n\r]/g, ' ').trim();
    results.push(data);
  })
  .on('end', () => {
    // 写入处理后的TSV文件
    const csvWriter = createCsvWriter({
      path: outputFile,
      header: Object.keys(results[0]).map(key => ({ id: key, title: key })),
      fieldDelimiter: '\t',
      quoting: true
    });

    csvWriter.writeRecords(results).then(() => console.log('TSV文件处理完成'));
  });

方法2:使用正则表达式直接处理文件内容

如果不想依赖第三方库,也可以用正则直接处理文件字符串:

const fs = require('fs');

const inputFile = 'example.tsv';
const outputFile = 'formatted_example.tsv';

// 读取文件并处理
fs.readFile(inputFile, 'utf8', (err, content) => {
  if (err) {
    console.error(err);
    return;
  }
  // 仅替换双引号内的换行
  const formattedContent = content.replace(/(?<="[^"]*)\s*\n\s*(?=[^"]*")/g, ' ');
  
  fs.writeFile(outputFile, formattedContent, 'utf8', (err) => {
    err ? console.error(err) : console.log('TSV文件处理完成');
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 03:35:18