首页 > 解决方案 > Python SQLite 数据库结果包含不需要的括号和引号

问题描述

我正在做 Coursera 课程“使用 Python 使用数据库”的作业,在其中一个作业中我遇到了这个问题,我返回的数据库结果的列周围有括号和引号。(它应该返回 orgiupui.edu而不是我当前的结果['iupui.edu']

请参考我下面的代码:

import sqlite3
import re

conn = sqlite3.connect('emaildb.sqlite')
cur = conn.cursor()

cur.execute('DROP TABLE IF EXISTS Counts')

cur.execute('''
CREATE TABLE Counts (org TEXT, count INTEGER)''')

fname = input('Enter file name: ')
if (len(fname) < 1): fname = 'mbox-short.txt'
fh = open(fname)
for line in fh:
    if not line.startswith('From: '): continue
    pieces = line.split()
    email = pieces[1]
    org = str(re.findall('@(\S+)', email))
    cur.execute('SELECT count FROM Counts WHERE org = ? ', (org,))
    row = cur.fetchone()
    if row is None:
        cur.execute('''INSERT INTO Counts (org, count)
                VALUES (?, 1)''', (org,))
    else:
        cur.execute('UPDATE Counts SET count = count + 1 WHERE org = ?',
                    (org,))

conn.commit()

# https://www.sqlite.org/lang_select.html
sqlstr = 'SELECT org, count FROM Counts ORDER BY count DESC LIMIT 10'

for row in cur.execute(sqlstr):
    print(str(row[0]), row[1])

cur.close()

mbox 文件在这里:https ://www.py4e.com/code3/mbox.txt 我觉得我不应该将 org 转换为字符串类,但我不知道还有什么可以转换的,因为我会大大感谢您的帮助,因为我已经尝试修复它几个小时了!

标签: pythonsqlpython-3.xsqlite

解决方案


这与您如何保存它有关:

org = str(re.findall('@(\S+)', email))

在这里,您可以找到所有电子邮件组织,对吗?但是你如何处理它们?不是采用第一个值,而是将其转换为字符串。这就是问题所在。findall返回一个列表,即使只有一个结果。这是你可以做的:

org = re.findall('@(\S+)', email)[0]

现在,org仍然是一个字符串,但它不再有括号,因为您没有将列表转换为字符串。


推荐阅读