簡體   English   中英

將元組列表導出到 TSV 時如何刪除括號和引號

[英]How to remove brackets and quotations when exporting a list of tuples to TSV

我有一個列表,打印時看起來像:

[(('1321', '01'), ('MessageXZY', '02'), ('DescriptionSKS', '03'), ('S7_6', '04'), ('S7_3', '05')), (('0A3B', '06'), ('MessageZYA', '07'), ('DescriptionKAM', '08')), (('9K44', '09'), ('MessageYAL', '10'), ('DescriptionAUS', '11'), ('S7_2', '12'))]

當我使用以下代碼導出時:

with open('HTML to TSV.tsv','w',encoding='ISO-8859-1') as out:
    tsv_out = csv.writer(out, delimiter="\t")
    for row in grouped_tuples:
        tsv_out.writerow(row)

我在文本/TSV 文件中得到以下內容:

('1321', '01')  ('MessageXZY', '02')    ('DescriptionSKS', '03')    ('S7_6', '04')  ('S7_3', '05')
('0A3B', '06')  ('MessageZYA', '07')    ('DescriptionKAM', '08')
('9K44', '09')  ('MessageYAL', '10')    ('DescriptionAUS', '11')    ('S7_2', '12')

期望的輸出:

1321, 01     MessageXZY, 02     DescriptionSKS, 03     S7_6, 04     S7_3, 05
0A3B, 06     MessageZYA, 07     DescriptionKAM, 08
9K44, 09     MessageYAL, 10     DescriptionAUS, 11     S7_2, 12

我寧願不從條目中搜索和刪除')作為我的實際字符串我合法地包含該組合。 我該怎么做才能讓csv.writer()不寫這些字符?

在編寫它們之前,您可以將這些對組合在一起:

import csv

grouped_tuples = [(('1321', '01'), ('MessageXZY', '02'), ('DescriptionSKS', '03'), ('S7_6', '04'), ('S7_3', '05')), (('0A3B', '06'), ('MessageZYA', '07'), ('DescriptionKAM', '08')), (('9K44', '09'), ('MessageYAL', '10'), ('DescriptionAUS', '11'), ('S7_2', '12'))]

with open('HTML to TSV.tsv','w', encoding='ISO-8859-1', newline='') as out:
    tsv_out = csv.writer(out, delimiter="\t")

    for row in grouped_tuples:
        tsv_out.writerow(', '.join(pair) for pair in row)

給你:

1321, 01    MessageXZY, 02  DescriptionSKS, 03  S7_6, 04    S7_3, 05
0A3B, 06    MessageZYA, 07  DescriptionKAM, 08
9K44, 09    MessageYAL, 10  DescriptionAUS, 11  S7_2, 12

代替

    tsv_out.writerow(row)

    tsv_out.writerow((row[0],row[1]))

暫無
暫無

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

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