我使用python3.4从mysql数据库表中提取。我使用csv模块将数据库中的数据行写入.CSV格式。现在我正在努力找出如何通过关键字来检查数据行,这些关键字可能会显示在第四列数据中(第[3]行)。我正在考虑使用re module
如下,但我一直在收到错误。是否无法在字符串类型的字段中搜索关键字,并在具有这些关键字的情况下过滤这些结果?我一直在收到错误。请帮忙
import re
import csv
userdate = input('What date do you want to look at?')
query = ("SELECT *FROM sometable WHERE timestamp LIKE %s", userdate)
keywords = 'apples', 'bananas', 'cocoa'
# Execute sql Query
cursor.execute(query)
result = cursor.fetchall()
#Reads a CSV file and return it as a list of rows
def read_csv_file(filename):
"""Reads a CSV file and return it as a list of rows."""
for row in csv.reader(open(filename)):
data.append(row)
return data
f = open(path_in + data_file)
read_it = read_csv_file(path_in + data_file)
with open('file.csv', 'wb') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for row in data:
match = re.search('keywords, read_it)
if match:
spamwriter.writerow(row)
答案 0 :(得分:0)
我放弃了正则表达式并使用了
for row in data:
found_it = row.find(keywords)
if found_it != -1:
spamwriter.writerow(row)