我的搜索字词只打印列表中的最后一个术语而不是找到的术语[Python 2.7.6]

时间:2014-02-01 02:49:07

标签: python list

我正在使用praw(reddit)api在帖子中搜索一组单词的评论,并返回该单词。基本上,我的单​​词列表很好......只是一个单词列表:

right = [ 'i', 'he', 'she', 'it', 'we', 'have', 'has']

这是我导入的words.py内部。我通过迭代将它保存到变量中:

for word in words.right:
    za = word
    print za

当我打印za时,它会打印出单词中的每个单词。就像我想要的那样。它打印:

i
he
she
it
we
have
has

我的程序返回包含其中一个搜索词的注释,就像这样:

for comment in flat_comment_generator:

    try:
        if za in comment.body.lower() and comment.id not in already_done:


            fob.write(comment.id + "\n")
            print comment.body
            print za

但是当我使用print za时,它只打印za中的最后一个术语,而不是它在程序中找到的术语。例如,它可能会返回:

"Comment found = Yeah, I really like basketball" "Search term = has"

所以一切正常,直到我要求它返回那个特定的术语。

1 个答案:

答案 0 :(得分:4)

我无法从您的代码中看到,如果搜索注释中的所有单词,za将仅包含单词列表的最后一个值。你可以在每次循环时看到你打印的所有单词,但如果你这样做,你就不会得到所有单词:

for word in words.right:
    za = word
print za

我想你要做的是:

for comment in flat_comment_generator:

    try:
        if comment.id not in already_done:
           terms = []
           # Search all the terms
           for word in words.right:
               if word in comment.body.lower():
                   terms.append(word)

           # If any term is in the comment
           if len(terms) != 0:
               fob.write(comment.id + "\n")
               print comment.body
               print terms

我希望它有所帮助,否则只是问。