繁体   English   中英

将与if函数相关的元素的附加结果附加到csv的最后一列

[英]Appending results of an element related if function to the last column of a csv

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

在下面的示例数据中,如果第3列包含表格,则我想根据第3列中的单词表(基于0的引用)来生成第6列,使第5列(第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

很快,您可以执行以下操作:

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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM