我编写了一个粗略的Python程序,用于从CSV文件中的索引中提取短语,并将这些行写入另一个文件.
import csv
total = 0
ifile = open('data.csv', "rb")
reader = csv.reader(ifile)
ofile = open('newdata_write.csv', "wb")
writer = csv.writer(ofile, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL)
for row in reader:
if ("some text") in row[x]:
total = total + 1
writer.writerow(row)
elif ("some more text") in row[x]:
total = total + 1
writer.writerow(row)
elif ("even more text I'm looking for") in row[x]:
total = total + 1
writer.writerow(row)
< many, many more lines >
print "\nTotal = %d." % total
ifile.close()
Run Code Online (Sandbox Code Playgroud)
我的问题是:是不是有更好的(更优雅/更简洁)Pythonic方式来做到这一点?我觉得这是一个不知道我不知道的情况.我正在搜索的CSV文件不大(3863行,669 KB),所以我认为没有必要使用SQL来解决这个问题,尽管我当然对此持开放态度.
我是一名Python新手,热爱语言并通过正常渠道(书籍,教程,Project Euler,Stack Overflow)自学.
任何建议都非常感谢.
你正在寻找any
一个生成器表达式:
matches = "some text", "some more text", "even more text I'm looking for"
for row in reader:
if any(match in row for match in matches):
total += 1
writer.writerow(row)
Run Code Online (Sandbox Code Playgroud)
或者,您可以一次写下所有行:
writer.writerows(row for row in reader if any(match in row for match in matches))
Run Code Online (Sandbox Code Playgroud)
但正如所写,并没有让你得到一个总和.