0

我一直在通过堆栈溢出寻找一个简单的示例,用于将 if 语句的结果作为 csv 中的新列附加。

使用下面的示例数据,如果第 3 列包含表使第 5 列(第 6 列),那么我想根据第 3 列(基于 0 的参考)中单词表的存在来生成第 6 列,"table exists"但是如果不包含,则使其包含"No table found"

示例数据:

title1,title2,title3,Table or no table?,title4
data,text,data,the cat sits on the table,text,data
data,text,data,tables are made of wood,text,data
data,text,data,the cat sits on the television,text,data
data,text,data,the dog chewed the table leg,text,data
data,text,data,random string of words,text,data
data,text,data,table seats 25 people,text,data
data,text,data,I have no idea why I made this example about tables,text,data
data,text,data,,text,data

期望的输出:

title1,title2,title3,Table or no table?,title4,Table exists?
data,text,data,the cat sits on the table,text,data,table exists
data,text,data,tables are made of wood,text,data,table exists
data,text,data,the cat sits on the television,text,data,No table found
data,text,data,the dog chewed the table leg,text,data,table exists
data,text,data,random string of words,text,data,No table found
data,text,data,table seats 25 people,text,data,table exists
data,text,data,I have no idea why I made this example about tables,text,data,table exists
data,text,data,,text,data,No table found

这可能是一个非常简单的任务,但我目前是一个极端的初学者,这种类型的代码目前不在我的 python 库中。如果您有任何帮助,将不胜感激,感谢 GTPE

4

1 回答 1

4

很快你可以做这样的事情:

with open("input.csv", "r") as input_file:
    header = input_file.readline()[:-1] #this is to remove trailing '\n'
    header += ",Table exists?"
    output_lines = [header]

    for line in input_file:
         output_lines.append(line[:-1])
         if 'table' in line.split(",")[3]:
             output_lines[-1]+=",table exists"
         else:
             output_lines[-1]+=",No table found"

with open("output.csv", "w") as output_file:
    output_file.write("\n".join(output_lines))
于 2013-10-21T03:46:23.223 回答