【问题标题】:Python string comparison not working properlyPython字符串比较无法正常工作
【发布时间】:2023-03-28 07:10:01
【问题描述】:

这是我的脚本。

import MySQLdb import feedparser import string

def checkunique(t):
    #t1 = ''.join(filter(lambda c: c in string.printable, t))
    cur.execute("SELECT title from linkstwo")
    titles = cur.fetchall()
    for k in titles:
        #k1 = ''.join(filter(lambda c: c in string.printable, k))
        print "'%s'" % k
        if t == k:
            return False
    return True

db = MySQLdb.connect ("localhost","root",password,"torrents") print "DB connection successful" cur  = db.cursor()

url = "https://extratorrent.cc/rss.xml?type=popular&cid=4"

feed = feedparser.parse(url)

print "Parsing successful"


for post in feed.entries:
    t = post.title
    m = post.magneturi
    #print "'%s'" % t
    if checkunique(t):
       cur.execute("INSERT INTO linkstwo (title, maglink) VALUES ('%s', '%s')" % \
                    (t, m))
    db.commit()

print "Script ended"

它解析 RSS 提要并将任何新条目添加到数据库中。

我的问题是函数 checkunique 总是返回 true 并且我不断收到重复的条目。我尝试了一些解决方案来删除任何可能已经进入的不可打印字符,但仍然没有运气。

【问题讨论】:

  • 顺便说一句,这是检查唯一性的一种非常低效的方法。您一次又一次地选择所有标题......只需在数据库表中放置一个唯一约束并在它们被触发时获取重复错误。
  • 你不应该使用 k[0] 来比较吗?您的名为titles 的变量应该是一个元组的元组。
  • 这是我希望构建的真实脚本的测试脚本。我必须以这种方式比较标题,因为我还将将新标题添加到单独的表(下载数据库)中。该表中的数据将用于在单独的脚本中下载相关的种子。
  • Mateusz Kleinert。你是救生员。谢谢你。为此,我花了将近 3 个小时的时间。

标签: python parsing mysql-python string-comparison


【解决方案1】:

每次执行checkunique 函数时查询所有表是没有意义的。

我会采用其他方法,您可以更新 sql 查询以检查标题是否已经存在。

例如:

cur.execute("IF (NOT EXISTS(SELECT title FROM linkstwo WHERE title = '%s' ))
    INSERT INTO linkstwo (title, maglink) VALUES ('%s', '%s')" \
                    (t, t, m)))

【讨论】:

  • 使用 sql 查询来实现我的目标有很多方法,但在这里我实现它的方法很重要,因为我依赖该方法来进一步构建我的脚本。
【解决方案2】:

将我的脚本编辑为此后,它开始按预期运行。

for k in titles:
        #k1 = ''.join(filter(lambda c: c in string.printable, k))
        print "'%s'" % k
        if t == k[0]:
            return False
    return True

【讨论】:

    猜你喜欢
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2022-01-16
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多