我正在使用 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/