python - 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 转换为字符串类,但我不知道还有什么可以转换的,因为我会大大感谢您的帮助,因为我已经尝试修复它几个小时了!
解决方案
这与您如何保存它有关:
org = str(re.findall('@(\S+)', email))
在这里,您可以找到所有电子邮件组织,对吗?但是你如何处理它们?不是采用第一个值,而是将其转换为字符串。这就是问题所在。findall
返回一个列表,即使只有一个结果。这是你可以做的:
org = re.findall('@(\S+)', email)[0]
现在,org
仍然是一个字符串,但它不再有括号,因为您没有将列表转换为字符串。
推荐阅读
- r - 如何自动限制 rpivottable 中的视图以符合数据保护要求
- javascript - 根据属性将对象数组拆分为三个单独的数组
- google-maps - 如何在颤动中的当前位置创建圆圈
- apache-spark - YARN worker 磁盘空间不足
- ruby-on-rails - 使用 Ruby On Rails 中的 Devise-jwt 作为后端和 Vuejs 作为前端的用户身份验证
- mysql - 如何在一个 sql 查询中计算多个表中的行数
- css - 在单独的 React 组件中集成引导程序和物化 css
- kubernetes - Kubernetes 可以 telnet 进入 POD 但不能 curl 网页内容
- signalr - SignalR 海报可用性
- vhdl - 如何在 vhdl 中声明自定义库?