【发布时间】:2014-07-13 12:14:41
【问题描述】:
我正在编码以从文本文件中查找名称和爱好并将其存储在详细信息(mysql 表)中。详细信息表由“名称”和“爱好”组成。我无法存储到我的数据库中。
import MySQLdb
import re
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="mysql", # your password
db="sakila") # name of the data base
cursor = db.cursor()
with open('qwer2.txt','r') as file:
for line in file:
patterns = [
a,b= re.compile('My name is (\w+) and my hobby is (\w+)\.', re.IGNORECASE),
a,b= re.compile('Me (\w+) and my interest is (\w+)\.', re.IGNORECASE),
]
match_result = patterns[0].match(line) or patterns[1].match(line)
name, hobby = match_result.groups()
cursor.execute('''INSERT into Details (Names, Hobby)
values (? , ?)'''%(a,b)
我的文本文件是一个段落:
My Name is Casssandra and my Hobby is Cooking.
My name is Archana and my hobby is Playing.Me Adarsh and my interest is Programming.
Me Leela and my interest is Baking.My name is John and my interest is Gaming.
输出:
Names | Hobby
Cassandra Cooking
Archana Playing
Adarsh Programming
Leela Baking
John Gaming
请帮我纠正我的程序以存储到表中。
【问题讨论】:
-
如果爱好是
dancing and singing -
请修改我的整个程序,每次修改后我的程序越来越差。
-
您的代码涉及两件事 1.) 正则表达式 2.) 数据库
-
如果 name 包含 first name last name 会怎样。我已经在我的帖子中添加了这部分。