【问题标题】:regex parse store in mysql正则表达式解析存储在mysql中
【发布时间】: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 会怎样。我已经在我的帖子中添加了这部分。

标签: python mysql regex


【解决方案1】:

您将 SQL 参数与字符串格式混合在一起,这是行不通的。将参数作为 单独的 参数传入:

cursor.execute('''INSERT into Details (Names, Hobby)
                  values (%s, %s)''', (name, hobby))
db.commit()

在使用 MySQLdb 数据库适配器时,需要使用%s 作为占位符,并且还需要提交事务。

您的patterns 设置不是有效的 Python;如果你想匹配多个模式,那就把它做成一个合适的列表:

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),
)

然后循环遍历这些模式直到匹配到一个:

for pattern in patterns:
     match_result = pattern.match(line)
     if match_result:
         name, hobby = match_result.groups()

演示:

>>> 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),
... )
>>> lines = '''\
... 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.
... '''.splitlines()
>>> for line in lines:
...     for pattern in patterns:
...         match_result = pattern.match(line)
...         if match_result:
...             name, hobby = match_result.groups()
...             print(name, hobby)
... 
('Casssandra', 'Cooking')
('Archana', 'Playing')
('Leela', 'Baking')

所有放在一起就变成了:

import MySQLdb
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),
)
db = MySQLdb.connect(host="localhost", # your host, usually localhost
                     user="root", # your username
                      passwd="mysql", # your password
                      db="sakila") # name of the data base

with open('qwer2.txt','r') as file, db as cursor:
    for line in file:
        for pattern in patterns:
             match_result = pattern.match(line)
             if match_result:
                 name, hobby = match_result.groups()
                 cursor.execute(
                     '''INSERT INTO Details (Names, Hobby)
                        VALUES (%s, %s)''',
                     (name, hobby))
                 break

这也将数据库连接用作上下文管理器(它为您提供一个游标),当with 块完成且没有错误时,它会自动提交更改。

【讨论】:

  • @adarshram:那么您匹配的名称不符合数据库列约束。创建更大的列或跳过此类名称。
  • 我的名字与数据库列匹配,创建更大的列/跳过这样的名称是什么意思?我的意思是插入它只是创建所以需要使列更大?
  • @adarshram:您的表架构对每一列都有约束。假设它是 VARCHAR(100) 列,那么您最多只能在该列中容纳 100 个字符的名称。您尝试插入的名称大于该限制。
  • 效果很好!因为我提到了它的一个段落,所以很多名字都没有被取走,但它从单独的行中得到了完美。但它没有取自一个句子,例如:“我 Leela,我的兴趣是烘焙.我的名字是约翰,我的兴趣是游戏。“它需要 leela 和爱好,但不是约翰和爱好。这就是问题所在?有没有办法解决这个问题?
  • @adarshram:那是因为一行有两个句子; re.search() 只会找到第一个匹配项,而不是所有匹配项。然后使用re.findall() 并遍历所有结果。但是,您不能在 cmets 中不断提出新问题;这并没有真正扩展。如果您继续为此苦苦挣扎,请提出一个新问题。
【解决方案2】:

从索引 2 和 4 中获取匹配组。

/(?:(My Name is|Me) )(.*?) and (?:my (Hobby|interest) is )([^\\.]*)./i

Online demo

示例代码:

import re
p = re.compile(ur'(?:(My Name is|Me) )(.*?) and (?:my (Hobby|interest) is )([^\\.]*).', re.IGNORECASE)
test_str = u"..."

re.findall(p, test_str)

【讨论】:

  • 首先使用上面匹配 singing and dance 的正则表达式从行中提取所需数据。插入数据库是单独的任务。
  • 首先执行代码提取 vales,然后扩展您的代码以将其插入数据库。我对数据库插入代码一无所知。
  • 您能否提供使用您的代码后提取的输出示例?
【解决方案3】:

您已经正确定义了游标,您唯一需要做的就是执行 SQL 语句,您可以通过在游标对象上调用 execute 来完成。另外,我建议您查看 MySQLDB 文档。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    相关资源
    最近更新 更多