解析,插入表格时出错

时间:2014-07-13 06:30:31

标签: python mysql mysql-python

我在解析和插入数据库时​​遇到了错误代码' a'没有定义。我有一个由姓名和爱好组成的文本文件。

qwer2.txt

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.

我的节目:

import MySQLdb
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:
        if "My Name is" in line:
             a = line[line.index(key) + 1]
        if "hobby is" in line:
             b =  line[line.index(key) + 1]

        if "Me" in line:
             a = line[line.index(key) + 1]
        if "my interest" in line:
             b =  line[line.index(key) + 1]             
        cursor.execute('''INSERT into Details (Names, Hobby)
                          values (? , ?)'''%(a, b))
db.commit()
db.close()

我收到的错误是“未定义/ b未定义/未定义的密钥'。我需要将数据库更新为名称和业余爱好”

期望的输出:

Names      |  Hobby

Cassandra   Cooking  
Archana     Playing
Adarsh      Programming
Leela       Baking
John        Gaming

请帮助!我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

我认为你需要正则表达式来解析文件。根据您的示例文本文件,我假设每条线路有两种不同的格式。以下是解析名称和爱好的示例脚本。

import re

patterns = [
    re.compile('My name is (\w+) and my hobby is (\w+)\.', re.IGNORECASE),
    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()

line变量可能不符合模式。您应该修改正则表达式模式,并在需要时进行一些错误检查。