如何使用cursor.fetchall与pyodbc从数据库的行中创建列表?
我有一个脚本,可以在一个简单的列表上正常工作。它从单词列表中删除一些不需要的字符,使它们相互匹配并返回几个相似单词列表(0.6的比例)。如何使用cursor.fetchall与pyodbc从数据库的行中创建列表?
但现在我需要它在Access数据库上工作。 我认为如果我在crsr.fetchall()上做了一个for循环并将所有项目放入一个列表(“单词”)中,那么它可以像以前那样工作。不幸的是它并没有,我真的想不通出来...
这里是我的代码:
# -*- coding: utf-8 -*-
import pyodbc
import re
from difflib import SequenceMatcher
[x for x in pyodbc.drivers() if x.startswith('Microsoft Access Driver')]
# Connection to accdb
conn_str = (
r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
r'DBQ=C:\\Users\\alice\\Desktop\\lexique3.accdb;'
)
cnxn = pyodbc.connect(conn_str)
crsr = cnxn.cursor()
# Put all words into a list
crsr.execute('SELECT unites_lexicales FROM Mot;')
result1 = crsr.fetchall()
words = []
for item in result1 :
words.append[item]
print(words)
在这一点上,我得到了一个错误:
TypeError: 'builtin_function_or_method' object is not subscriptable
我试着与范围迭代:
crsr.execute('SELECT unites_lexicales FROM Mot;')
result = crsr.fetchall()
words = []
for i in range(0, len(result)) :
words.append(result[i])
print(words)
但我看起来像这样的项目列表,它不是满足所有:
[('anbaglé',), ('anfoutan',), ('òrdinè',), ('alakous',), ('ayen',), ('anmè',), ('antòtiyé',),...]
这里是一个非常完美的简单列表中的其余代码:
radicals = []
motifp = "^(re|em|dés)"
motifs = "(iste|ment|er|ant|able)$"
for word in words :
word = re.sub(motifp, '', word)
word = re.sub(motifs, '', word)
radicals.append(word)
print(radicals)
ratio = 0.6
n = len(radicals)
result = []
used_js = []
for i in range(n):
if i in used_js:
continue
matches = [words[i]]
js = (x for x in range(n) if x != i and x not in used_js)
for j in js:
if SequenceMatcher(None, radicals[i], radicals[j]).ratio() >= ratio :
matches.append(words[j])
used_js.append(j)
result.append(matches)
print(result)
下面是我通过测试它的简单罗列在早期得到了结果:
[['flore', 'fleur', 'fleuriste'], ['remaniement', 'remanier', 'manier', 'maniable'], ['désaimer', 'aimant', 'aimer'], ['désemmêler', 'emmêler', 'mêler']]
我必须得到整个游标部分错误,我真的不明白这是如何工作的......感谢您的帮助!
您可以用索引将每一行索引。此行只有一列,因此您可以使用0.您也可以通过名称对其进行索引。
# ...
crsr.execute('SELECT unites_lexicales FROM Mot;')
result = crsr.fetchall()
words = []
for row in result:
# words.append(row['unites_lexicales'])
words.append(row[0])
print(words)
# ...
你也可以使用列表理解来获得第一列。
# ...
crsr.execute('SELECT unites_lexicales FROM Mot;')
result = crsr.fetchall()
# words = [row['unites_lexicales'] for row in result]
words = [row[0] for row in result]
print(words)
# ...
谢谢!它在我单独尝试时有效:我有我的单词列表,我也有我的单词列表,但是当我尝试一切时,我什么都没有。没有错误信息,没有文字,只有黑屏......任何线索? –
即使列表理解仍然没有任何反应...... –
当我尝试使用['unites_lexicales']时,出现以下错误:TypeError:行索引必须是整数,而不是str –
在你的第一个代码片段中,你正在使用words.append [item]。你应该使用words.append(item)。追加是一种方法。 – Kyle
好的,谢谢,但是有什么办法可以将这一栏中的项目放入列表中? –
从fetchall()返回的行表现如同元组,但您也可以通过名称访问列。在循环中尝试** words.append(item ['unites_lexicales'])**或** words.append(item [0])**。有一些很好的例子[在这里通过文档](https://github.com/mkleehammer/pyodbc/wiki/Getting-started#selecting-some-data)。 – Kyle