我遇到了一个不适的问题,我正在阅读带有类似条款的CSV文件:

4,[the mentalist, dodgeball, meet the fockers]
5,[godfather, the heat, friends]
...

我使用CSV模块读取此Python,并且通常ID做:

import ast
x=ast.literal_eval(row[1])

但是,这显然失败了,因为未引用列表条目。

我如何解决这个问题? :(

分析解答

这个"format"真的不幸解析(例如,如果电影的名称包含,怎么办?那么我不知道该如何解析该文件)。

最好的选择是将其修复在源中(文件的生成方式)。

如果您无法修复文件的生成方式,则可以尝试:

with open("data.csv", "r") as f_in:
    for line in map(str.strip, f_in):
        if not line:
            continue
        row = line.split(",", maxsplit=1)
        if "[" in row[1]:
            row[1] = row[1].strip("[]").split(", ")
        print(row)

printing:

['col1', 'col2']
['4', ['the mentalist', 'dodgeball', 'meet the fockers']]
['5', ['godfather', 'the heat', 'friends']]

data.csv包含:

col1,col2
4,[the mentalist, dodgeball, meet the fockers]
5,[godfather, the heat, friends]