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

标签 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 时,它会打印出 words.right 中的每个单词,就像我想要的那样。它打印:

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"

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

最佳答案

我无法从您的代码中看出如何搜索评论中的所有单词,因为 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

希望对你有帮助,否则就问吧。

关于python - 我的搜索词只打印列表中的最后一个词而不是找到的词 [Python 2.7.6],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21493545/

相关文章:

python - MATLAB打开带有savemat写的汉字的.mat文件时报错

python - Python 中的列表与元组情况

python - 如何打印内部列表包含字符串和字符串列表的列表列表?

python - 将 igraph 中的图保存为 eps 格式

python - “Can' t 实例化抽象类……在不应该有任何抽象方法的类上使用抽象方法”

python - Django 是否以某种方式缓存 url 正则表达式模式?

python - 如何将包含列表列表的文件转换为字符串?

python - 如何在 PyCharm 中禁用此示例程序?

scala - 计算元素出现的次数

python - 如何在python中获取锯齿状数组的长度