Python字符串比较无法正常工作

时间:2017-02-08 20:14:46

标签: python parsing mysql-python string-comparison

这是我的剧本。

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并且我不断收到重复的条目。我尝试了一些解决方案来删除可能已经找到它的任何不可打印的字符,但仍然没有运气。

2 个答案:

答案 0 :(得分:0)

每次执行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)))

答案 1 :(得分:0)

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

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