如何处理读取csv的问题,csv是一个分号分隔的文件,其中某些字符串包含分号?

2024-06-25 23:08:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题可以通过在csv(分号分隔)文件中显示几个示例行来说明,如下所示:

4;1;"COFFEE; COMPANY";4
3;2;SALVATION ARMY;4

注意,在一行中,一个字符串用引号括起来,里面有一个分号(在我的输入文件中,除了那些包含分号的列之外,没有任何列在它们周围都有引号)。在

这些带有引号和分号的行导致了一个问题——基本上,我的代码正在计算列/字段内引号内的分号。因此,当我在这一行中读取时,它会将字符串中的分号作为分隔符读取,从而使这一行看起来像是有一个额外的字段/列。在

期望的输出如下所示,在“coffee company”前后没有引号,在“coffee”和“company”之间没有分号:

^{pr2}$

实际上,这篇关于“咖啡公司”的专栏文章对我来说毫无用处,所以最后的文件也可以是这样的:

4;1;xxxxxxxxxxx;4
3;2;xxxxxxxxxxx;4

我怎样才能去掉这一列中的分号,而不去掉其他分号呢?在


Tags: 文件csv字符串代码示例company引号coffee
2条回答

下面是一种使用Pandas库的替代方法,它使您不必为循环编写代码:

import pandas as pd

#Read csv into dataframe df
df = pd.read_csv('data.csv', sep=';', header=None)
#Remove semicolon in column 2
df[2] = df[2].apply(lambda x: x.replace(';', ''))

这给出了以下数据帧df:

^{pr2}$

Pandas提供了几个内置函数来帮助您操作数据或得出统计结论。使用表格格式的数据也可以使处理数据更直观。在

csv模块可以轻松处理这样的作业:

# Contents of input_file.csv
# 4;1;"COFFEE; COMPANY";4
# 3;2;SALVATION ARMY;4

import csv
input_file = 'input_file.csv'  # Contents as shown in your question.

with open(input_file, 'r', newline='') as inp:
    for row in csv.reader(inp, delimiter=';'):
        row[2] = row[2].replace(';', '')  # Removed embedded ';' chars.
        # If you don't care about what's in the column, use the following instead:
        # row[2] = 'xxxxxxxxxxx'  # Value not needed.
        print(';'.join(row))

打印输出:

^{pr2}$

后续问题:如何将此数据写入新的csv文件?在

import csv
input_file = 'input_file.csv'  # Contents as shown in your question.
output_file = 'output_file.csv'

with open(input_file, 'r', newline='') as inp, \
     open(output_file, 'w', newline='') as outp:
    writer= csv.writer(outp, delimiter=';')
    for row in csv.reader(inp, delimiter=';'):
        row[2] = row[2].replace(';', '')  # Removed embedded ';' chars.
        writer.writerow(row)

相关问题 更多 >