【问题标题】:Why my data loop multiple times when I created dictionary?为什么我创建字典时数据循环多次?
【发布时间】:2020-01-31 02:20:18
【问题描述】:

第一步从 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

【问题讨论】:

  • 什么是row['g']?您只选择了a
  • 你在哪里执行INSERT查询?
  • 哦……抱歉……我已经编辑过了……
  • row['a'] 是如何工作的? fetchall() 返回元组列表,而不是字典列表。

标签: python python-3.x for-loop


【解决方案1】:

您正在迭代具有 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

您可以将您的insert 添加到data 的每一行中,或者您可以稍后通过再次循环您的data 列表来单独插入它。

【讨论】:

    【解决方案2】:

    您在每次拼写更正后执行查询,因此您插入了所有中间结果。在所有更正之后,您应该只做一次。

    你可以在处理完所有行后只调用一次mysql.connection.commit(),它不需要在循环中。

    row['a'] 应该是 row[0],因为 fetchall() 返回的是元组列表,而不是字典。

    for row in data:
        for k, v in dikk.items():
            t = re.compile(re.escape(k), re.IGNORECASE)
            row[0] = t.sub(v, row[0])
        print(row[0])
        mySql_insert_query = """INSERT INTO table2 (a) VALUES (%s)"""
        cur.execute(mySql_insert_query, (row[0],))
    mysql.connection.commit()
    

    还可以通过对re.sub() 的一次调用而不是循环来完成所有替换。将所有键转换为像key1|key2|key3|... 这样的正则表达式,并使用函数从字典中获取替换。

    t = re.compile("|".join(re.escape(k) for k in dikk))
    row['a'] = t.sub(lambda m: dikk[m.group(0)], row['a']
    

    【讨论】:

    • 是的...其实我已经完成了执行查询...但是,我忘了写在这里...sorry2
    • 这不会返回TypeError吗? fetchall() 返回一个元组列表,row 将遍历已调用 row['a'] 的元组?
    • @PacketLoss 如果问题中的代码有效,则它必须获取字典列表。
    • 必须是,但是我检查过的所有地方都显示fetchall()returning a list of tuples
    猜你喜欢
    • 1970-01-01
    • 2019-03-03
    • 2014-06-02
    • 2014-04-01
    • 1970-01-01
    • 2016-01-11
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多