python - 为什么我创建字典时数据循环多次?

标签 python python-3.x for-loop

第一步从从 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 个键值对的字典,并为每个循环调用 printinsert,导致其触发 3 次。

如果将对 insertprint 的调用移至循环外部,则每个元素都会有一个返回。

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/

相关文章:

java - Hiveserver2无法启动: “ascii codec cant encode character”

python - os.path模块如何工作?

python - bool 掩码 Groupby Any 并创建指标

python - PyCharm - 如何自动将项目中的所有标识符重命名为snake_case?

python - 如何在Python中集成包含r的一阶导数的r函数?

python - 为什么在安装 cx_freeze 后出现 "no module named cx_Freeze"错误?

python-3.x - 我想将国家列表与列数据进行比较,列数据是 pandas 数据框 Python 中的字典对象类型

java - 无法在 Java 中使用两个 for 循环单独取出

C# For 循环不递增

python - For 循环未迭代预期的时间量