第一步从从 mysql 获取数据开始。然后,我将使用我创建的字典进行拼写检查。最后,将输出插入mysql。问题是我的输出循环多次。希望你能帮助我
我的代码:
app.py
from dic import dikk
cur.execute("SELECT a FROM table WHERE id=%s", [id])
data = cur.fetchall()
for row in data:
for k, v in dikk.items():
t = re.compile(re.escape(k), re.IGNORECASE)
row['a'] = t.sub(v, row['a'])
print(row['a'])
mySql_insert_query = """INSERT INTO table2 (a) VALUES (%s)"""
records_to_insert =[(row['a'])]
cur = mysql.connection.cursor()
cur.execute(mySql_insert_query, records_to_insert)
# Commit to DB
mysql.connection.commit()
dic.py
dikk={'speling':'spelling','writen':'written','Jhon':'John'}
我得到的输出:
it is not Jhon
it is not Jhon
it is not John
我想要的输出:
it is not John
最佳答案
您正在迭代具有 3 个键值对的字典,并为每个循环调用 print
和 insert
,导致其触发 3 次。
如果将对 insert
和 print
的调用移至循环外部,则每个元素都会有一个返回。
dikk={'speling':'spelling','writen':'written','Jhon':'John'}
data = [('it is not Jhon',), ('you spell it speling',), ('writen is the way',)]
for idx, value in enumerate(data):
for word in value[0].split(" "):
if word in dikk.keys():
data[idx] = data[idx][0].replace(word, dikk[word])
# Insert can go here
for row in data:
print(row)
# Or insert can go here
#it is not John
#you spell it spelling
#written is the way
您可以将插入
添加到data
中的每一行,也可以稍后通过再次循环data
列表来单独插入。
关于python - 为什么我创建字典时数据循环多次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59997083/