如何正确读取csv格式错误的字符串

k97glaaz  于 2023-05-26  发布在  其他
关注(0)|答案(1)|浏览(138)

在csv中,对于列,字符串中存在歧义。因此,我在列表中获得6值,而不是5值作为输出。

代码:

import csv
csv_data = csv.reader(file('test.csv'))
for row in csv_data:
    print row

我尝试用space替换",以获得至少与不带引号的普通字符串相同的结果,如下所示:

for row in csv_data:
    print [r.replace('"',' ') for r in row] # This did't worked as expected.

输入:

csv文件中的行看起来像这样,

1,2,"text1", "Sample text ""present" in csv, as this",5

"Sample text "present" in csv, as this" # Error due to this value.

输出:

['1', '2', 'text1', 'Sample text present" in csv', 'as this', 5]

预期输出:

['1', '2', 'text1', 'Sample text "present" in csv, as this', 5]
r7s23pms

r7s23pms1#

这几乎是令人尴尬的黑客,但似乎至少在你的问题中显示的示例输入上有效。它的工作原理是对csvreader读取的每一行进行后处理,并尝试检测它们何时由于格式错误而被错误读取,然后进行纠正。

import csv

def read_csv(filename):
    with open(filename, 'rb') as file:
        for row in csv.reader(file, skipinitialspace=True, quotechar=None):
            newrow = []
            use_a = True
            for a, b in zip(row, row[1:]):
                # Detect bad formatting.
                if (a.startswith('"') and not a.endswith('"')
                        and not b.startswith('"') and b.endswith('"')):
                    # Join misread field backs together.
                    newrow.append(', '.join((a,b)))
                    use_a = False
                else:
                    if use_a:
                        newrow.append(a)
                    else:
                        newrow.append(b)
                        use_a = True
            yield [field.replace('""', '"').strip('"') for field in newrow]

for row in read_csv('fmt_test2.csv'):
    print(row)

输出:

['1', '2', 'text1', 'Sample text "present" in csv, as this', '5']

相关问题