CSV编写需要唯一定界符的文本字符串

问题描述 投票:1回答:3

我用python编写了HTML解析器,用于提取数据,使其在csv文件中看起来像这样:

    itemA, itemB, itemC, Sentence that might contain commas, or colons: like this,\n

所以我使用了一个delmiter“ :::::”认为它不会在数据中被挖掘

    itemA, itemB, itemC, ::::: Sentence that might contain commas, or colons: like this,::::\n

这适用于数千行中的大多数,但是,显然是冒号:当我在Calc中导入csv时,可以抵消它。

我的问题是,在创建带有许多需要用某种分隔符分隔的句子的csv时,最佳或唯一的分隔符是什么?我是否正确理解分隔符,因为它们将CSV中的值分开?

python csv delimiter openoffice-calc
3个回答
1
投票

[正如我在评论中非正式建议的那样,唯一性意味着您需要使用数据中不会包含的某些字符-chr(255)可能是个不错的选择。例如:

import csv

DELIMITER = chr(255)
data = ["itemA", "itemB", "itemC",
        "Sentence that might contain commas, colons: or even \"quotes\"."]

with open('data.csv', 'wb') as outfile:
    writer = csv.writer(outfile, delimiter=DELIMITER)
    writer.writerow(data)

with open('data.csv', 'rb') as infile:
    reader = csv.reader(infile, delimiter=DELIMITER)
    for row in reader:
        print row

输出:

 ['itemA', 'itemB', 'itemC', 'Sentence that might contain commas, colons: or even "quotes".']

如果您不使用csv模块,而是手动写入和/或读取数据,则它将像这样:

with open('data.csv', 'wb') as outfile:
    outfile.write(DELIMITER.join(data) + '\n')

with open('data.csv', 'rb') as infile:
    row = infile.readline().rstrip().split(DELIMITER)
    print row

2
投票

是的,定界符在CSV文件的每一行中分隔值。划定带有大量标点符号的文本有两种策略。首先,您可以引用这些值,例如:

Value 1, Value 2, "This value has a comma, <- right there", Value 4

第二种策略是使用制表符(即'\t')。

Python的内置CSV模块可以读取和写入使用引号的CSV文件。查看the csv.reader function下的示例代码。内置的csv模块将正确处理引号,例如它将转义值本身中的引号。


0
投票

CSV文件通常使用双引号csv.reader来包装可能包含诸如逗号之类的字段分隔符的长字段。如果该字段包含双引号,则使用反斜杠将其转义:"

© www.soinside.com 2019 - 2024. All rights reserved.