【问题标题】:Clear Tuple in Python after For LoopFor循环后在Python中清除元组
【发布时间】:2017-02-10 16:27:06
【问题描述】:

我正在努力弄清楚如何在从数据库读取后清除元组“数据”。

流程:

每 X 分钟,我调用一次 batchUpdate

batchUpdate 拉入符合特定条件的记录

我们遍历那些执行更新的记录

流程结束,等待下一次调用

问题:

随后对函数 batchUpdate 的每次调用都不会产生新数据。元组“数据”包含与以前相同的值。

简化示例(仅拉取一条记录,每 1 秒安排一次):

Update has started
((10938L, u"@anonymized @anonymized House of Cards will be nothing compared  to the Drumpf's!And worst of all is that Americans chose him as president?", u'New York, USA'),)
Update has started
((10938L, u"@anonymized @anonymized House of Cards will be nothing compared to the Drumpf's!And worst of all is that Americans chose him as president?", u'New York, USA'),)
Update has started
((10938L, u"@anonymized @anonymized House of Cards will be nothing compared to the Drumpf's!And worst of all is that Americans chose him as president?", u'New York, USA'),)
Update has started
((10938L, u"@anonymized @anonymized House of Cards will be nothing compared to the Drumpf's!And worst of all is that Americans chose him as president?", u'New York, USA'),)

代码:

class analyzeRecords():
    def batchUpdate(self):

     global data

     #Select up to 1 record

     b.execute(""" SELECT id, tweet,tweet_location_guess FROM rawTweets where compoundScore IS NULL LIMIT 0,1 """)

     #Put that data into a tuple

     data = b.fetchall()

     print(data)

     #print that update has started

     print("Update has started")

     for row in data:
          idMatch = row[0]
          cleanTweet = reduce(lambda x, y: x.replace(y, d[y]), sorted(d, key=lambda i: len(i), reverse=True), row[1].lower())
          sentimentScores = analyzer.polarity_scores(cleanTweet)
          overallScore = sentimentScores["compound"]

          u.execute("""UPDATE rawTweets SET tweet=%s, compoundScore=%s where id=%s""",
                    (cleanTweet, overallScore, idMatch))
          update.commit()

l = task.LoopingCall(analyzeRecords().batchUpdate)
l.start(timeout) # call every sixty seconds

reactor.run()       

【问题讨论】:

  • 我可能误会了。您可以简单地在函数末尾设置data = None 吗?
  • 但是b.execute 返回不同的数据?是否有任何理由将数据定义为全局数据?

标签: python for-loop tuples mysql-python


【解决方案1】:

在您的代码中,您正在执行这两行:

 global data

 data = b.fetchall()

综合起来,这两个语句应该会覆盖之前 data 变量中的任何内容。

我要指出,这个函数似乎需要一个全局变量——你可以并且可能应该只为此使用一个局部变量。

无论如何,我认为问题不在于存在一些神秘的剩余数据,除非定义了 b.fetchall() 对象来执行此操作。 (例如,如果您的查询中有错误,或者您的查询没有返回匹配项,它是如何传达这一点的?如果它引发或返回您忽略的值,那么 fetchall 可能会返回陈旧数据,因为您应该检查值而不是调用 fetchall...)

我建议你看看execute 和fetchall 是如何一起工作的,同时也看看你的for 循环。我看到b.execute 和u.execute 和update.commit。好像您有许多不同的数据库连接。也许你会。或者也许你复制/粘贴代码,你真的应该做这样的事情:

u.execute(...)
u.commit()

【讨论】:

  • 我对数据库连接/游标很愚蠢。问题已解决。谢谢!
猜你喜欢
  • 2018-07-05
  • 2023-03-28
  • 1970-01-01
  • 2022-12-10
  • 1970-01-01
  • 2015-03-13
  • 2019-06-30
  • 1970-01-01
  • 2015-10-21
相关资源
最近更新 更多