【问题标题】:keyword search in string from mysql using python?使用python从mysql的字符串中搜索关键字?
【发布时间】:2016-06-02 09:43:09
【问题描述】:

我正在使用 python3.4 从 mysql 数据库表中提取数据。我使用 csv 模块将数据库中的数据行写入 .CSV 格式。现在我正在尝试 toros 弄清楚如何通过可能出现在第四列数据(行 [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)               

【问题讨论】:

  • 您遇到什么错误?请编辑问题以包含该信息。
  • 这一行应该是:query = ("SELECT *FROM sometable WHERE timestamp LIKE %s", (userdate,)) 其中第二个参数是一个元组。

标签: mysql string python-3.x export-to-csv


【解决方案1】:

我放弃了正则表达式并使用了

for row in data:
    found_it = row.find(keywords)
    if found_it != -1:
         spamwriter.writerow(row)  

【讨论】:

    猜你喜欢
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多