我正在尝试使用 Python 解析 Twitter RSS 提要并将信息放入 sqlite 数据库中。这是一个例子:
MiamiPete: today's "Last Call" is now up http://bit.ly/MGDzu #stocks #stockmarket #finance #money
我想做的是为主要内容创建一栏(Miami Pete…now up),为 URL 创建一栏(http://bit.ly/MGDzu),以及四个单独的主题标签列(股票、股票市场、金融、货币)。我一直在研究如何做到这一点。
如有任何建议,我们将不胜感激!
附言下面是我一直在玩弄的一些代码——你可以看到我最初尝试创建一个名为“tiny_url”的变量并将其拆分,它似乎确实这样做了,但这种微弱的尝试并没有解决所指出的问题多于。 :)
def store_feed_items(id, items):
""" Takes a feed_id and a list of items and stored them in the DB """
for entry in items:
c.execute('SELECT entry_id from RSSEntries WHERE url=?', (entry.link,))
tinyurl = entry.summary ### I added this in
print tinyurl.split('http') ### I added this in
if len(c.fetchall()) == 0:
c.execute('INSERT INTO RSSEntries (id, url, title, content, tinyurl, date, tiny) VALUES (?,?,?,?,?,?,?)', (id, entry.link, entry.title, entry.summary, tinyurl, strftime("%Y-%m-%d %H:%M:%S",entry.updated_parsed), tiny ))
请您参考如下方法:
看来您的数据驱动设计存在相当大的缺陷。除非您的所有条目都有文本部分、一个 url 和最多 4 个标签,否则它不会起作用。
您还需要将保存到数据库与解析分开。可以使用正则表达式(甚至字符串方法)轻松完成解析:
>>> s = your_string
>>> s.split()
['MiamiPete:', "today's", '"Last', 'Call"', 'is', 'now', 'up', 'http://bit.ly/MGDzu', '#stocks', '#stockmarket', '#finance', '#money']
>>> url = [i for i in s.split() if i.startswith('http://')]
>>> url
['http://bit.ly/MGDzu']
>>> tags = [i for i in s.split() if i.startswith('#')]
>>> tags
['#stocks', '#stockmarket', '#finance', '#money']
>>> ' '.join(i for i in s.split() if i not in url+tags)
'MiamiPete: today\'s "Last Call" is now up'
不过,单表数据库设计可能不得不放弃。
