[英]How can I compare each element in first list with whole elements in the second list?
I'm very new to python, so I need your help . 我是python的新手,所以需要您的帮助。 I have csv file contains:
我的csv文件包含:
Name Movie_title Comments
Mark toy story love
Sam Grumpy Old Men cool
Mark Grumpy Old Men Hate it
Sam toy story didn't like it
I create a list contains only name without duplicate: names = ['Mark,Sam'] so what I want to create a text file with movie_title(eg, toy story.txt) contains all the comments in that movie 我创建了一个仅包含名称但没有重复的名称的列表:names = ['Mark,Sam'],所以我要创建带有movie_title的文本文件(例如,toy story.txt)包含该电影中的所有注释
Mark -- toy story (love the movie) 马克-玩具总动员(爱电影)
Sam -- toy story (didn't like it) 山姆-玩具总动员(不喜欢)
Sam -- Grumpy Old Men (cool) 山姆-脾气暴躁的老男人(酷)
Mark -- Grumpy Old Men (Hate it) 马克-脾气暴躁的老人(讨厌它)
with open('data.csv', 'rt') as f:
reader = csv.reader(f, delimiter=',')
next(reader)# skip header
for row in reader:
for name in names:
if name == row[0]:
for i in row[0]:
txt = open(os.path.join(dir_name, names + ".txt"),'w+')
newlist.append(name+row[2])
txt.write(newlist)
any idea !!!! 任何想法 !!!!
A bit simpler. 有点简单。 Because each line has the fields name, movie and comment (row[0], row[1] and row[2], respectively), you can just directly write everything from the fetched line:
因为每一行都有字段名称,电影和注释(分别为行[0],行[1]和行[2]),所以您可以直接从提取的行中编写所有内容:
#!/bin/python
import csv
with open('data.csv', 'rt') as f:
reader = csv.reader(f, delimiter=',')
next(reader)# skip header
for row in reader:
with open(row[1]+".txt","a") as mov:
mov.write(row[0]+" -- "+row[1]+" ("+row[2]+")\n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.