簡體   English   中英

如何在 Python 中將制表符分隔、管道分隔轉換為 CSV 文件格式

[英]How to convert tab separated, pipe separated to CSV file format in Python

我有一個文本文件 (.txt),可以是制表符分隔格式或管道分隔格式,我需要將其轉換為 CSV 文件格式。 我正在使用 python 2.6。 誰能建議我如何識別文本文件中的分隔符、讀取數據然后將其轉換為逗號分隔文件。

提前致謝

我擔心您在不知道分隔符是什么的情況下無法識別它。 CSV 的問題在於, 引用 ESR

Microsoft 版本的 CSV 是如何不設計文本文件格式的教科書示例。

如果定界符可以出現在字段中,則需要以某種方式對其進行轉義。 在不知道轉義是如何完成的情況下,自動識別它是困難的。 可以按照 UNIX 方式使用反斜杠“\”進行轉義,或者按照 Microsoft 方式使用引號進行轉義,引號也必須進行轉義。 這不是一項微不足道的任務。

所以我的建議是從生成您要轉換的文件的任何人那里獲得完整的文檔。 然后您可以使用其他答案或某些變體中建議的方法之一。

編輯:

Python 提供了csv.Sniffer可以幫助您推斷 DSV 的格式。 如果您的輸入如下所示(請注意第二行第一個字段中帶引號的定界符):

a|b|c
"a|b"|c|d
foo|"bar|baz"|qux

你可以這樣做:

import csv

csvfile = open("csvfile.csv")
dialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)

reader = csv.DictReader(csvfile, dialect=dialect)
for row in reader:
    print row,
# => {'a': 'a|b', 'c': 'd', 'b': 'c'} {'a': 'foo', 'c': 'qux', 'b': 'bar|baz'}
# write records using other dialect

您的策略可能如下:

  • 使用制表符分隔的 csv 閱讀器和管道分隔的 csv 閱讀器解析文件
  • 計算結果行的一些統計信息,以決定要寫入哪個結果集。 一個想法可能是計算兩個記錄集中的字段總數(預計制表符和管道不是那么常見)。 另一個(如果你的數據是強結構化的,並且你希望每行中的字段數相同)可以測量每行字段數的標准差,並獲取標准差最小的記錄集。

在以下示例中,您會發現更簡單的統計信息(字段總數)

import csv

piperows= []
tabrows = []

#parsing | delimiter
f = open("file", "rb")
readerpipe = csv.reader(f, delimiter = "|")
for row in readerpipe:
 piperows.append(row)
f.close()

#parsing TAB delimiter
f = open("file", "rb")
readertab = csv.reader(f, delimiter = "\t")
for row in readerpipe:
 tabrows.append(row)
f.close()

#in this example, we use the total number of fields as indicator (but it's not guaranteed to work! it depends by the nature of your data)
#count total fields
totfieldspipe = reduce (lambda x,y: x+ y, [len(f) for f in piperows])
totfieldstab = reduce (lambda x,y: x+ y, [len(f) for f in tabrows])

if totfieldspipe > totfieldstab:
 yourrows = piperows
else:
 yourrows = tabrows


#the var yourrows contains the rows, now just write them in any format you like

像這樣

from __future__ import with_statement 
import csv
import re
with open( input, "r" ) as source:
    with open( output, "wb" ) as destination:
        writer= csv.writer( destination )
        for line in input:
            writer.writerow( re.split( '[\t|]', line ) )
for line in open("file"):
    line=line.strip()
    if "|" in line:
        print ','.join(line.split("|"))
    else:
        print ','.join(line.split("\t"))

我建議從現有答案中獲取一些示例代碼,或者更好地使用 python 中的csv模塊並將其更改為首先假設制表符分隔,然后管道分隔,並生成兩個以逗號分隔的輸出文件。 然后您目視檢查這兩個文件以確定您想要哪個並選擇那個。

如果您實際上有很多文件,那么您需要嘗試找到一種方法來檢測哪個文件是哪個。
其中一個例子是這樣的:

if "|" in line:

這可能就足夠了:如果文件的第一行包含一個管道,那么可能整個文件都是管道分隔的,否則假設一個制表符分隔的文件。

或者修復文件以在第一行中包含一個易於識別的關鍵字段 - 或者第一行可能包含可以檢測到的列標題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM