【发布时间】:2016-07-20 02:55:47
【问题描述】:
所以我正在使用 reddit API 来监控销售 subreddit,并且我有这段代码:
if(any(w.lower() in re.search('%s(.*)%s' % ("[h]", "[w]"), i['data']['title'].lower()).group(1).lower() for w in wants)
and i['data']['id'] not in urls):
urls[i['data']['id']] = [i['data']['title'],i['data']['url']]
实际上,它采用 reddit 帖子标题,并选择该标题中 [w] 和 [h] 标记之间的所有文本。然后它会检查“wants”列表中定义的任何单词是否出现在标题中,如果出现,它将标题和 reddit 链接添加到数组中。
我测试过的一个例子是想要列表中的单词 ergodox,帖子标题是 [us-wi] [h] ergodox infinity (w/ sip socket mod) [w] 贝宝。但是帖子没有被添加到数组中,可能是因为上面的 if(any...) 语句从未验证为真,但我不明白为什么。
另一个问题一旦解决,有时 [h] 和 [w] 会以相反的方式出现,有什么捷径可以解决这个问题吗?还是需要对 if 语句进行 or 扩展?
提前致谢:)
编辑感谢评论,尝试简化也不起作用:
for w in wants:
if w.lower() in i['data']['title'].lower() and i['data']['id'] not in urls:
urls[i['data']['id']] = [[i['data']['title'],i['data']['url']]
【问题讨论】:
-
我建议在生成器表达式(或列表理解)之外将其分解,以使内容更具可读性。在此过程中,您最终会简化代码并使错误更加明显。
-
@RafaelBarros 我之前确实尝试过,我将编辑帖子并提供我尝试过的代码,它也没有工作......
-
wants中有什么内容? -
您知道
[]字符在正则表达式中具有特殊含义吗? -
@RafaelBarros 这是最简单的事情!我觉得发帖很傻,所有排序,你能把你的评论作为答案吗? :)
标签: python python-2.7 reddit