Python: TypeError: 'Comment'类型的对象不可迭代
我正在尝试编写一个简单的reddit机器人,它会进入一个子版块,查看帖子,读取评论。如果评论中出现“feels”这个词,它就会发一个“feels”的动图。但是我遇到了一个错误:'TypeError: argument of type 'Comment' is not iterable',这个错误出现在我尝试执行has_feels = 'feels' in comment的时候。
我的代码:
import praw
import time
r = praw.Reddit('Posts Feels gif in response to someone saying feels'
'by: Mjone77')
r.login('Feels_Bot', 'notrealpassword')
already_done = []
feels = ['feels']
while True:
subreddit = r.get_subreddit('bottest')
for submission in subreddit.get_new(limit=10):
#submission = next(submissions)
commentNum = 0
for comment in submission.comments:
print(comment)
print(comment.id)
has_feels = 'feels' in comment
if comment.id not in already_done and has_feels:
#comment.reply('[Relevant](http://i.imgur.com/pXBrf.gif)')
already_done.append(comment.id)
print('Commented')
time.sleep(1800)
错误报告(前两行是代码运行到出错之前的打印输出):
The feels are strong
ciafpqn
Traceback (most recent call last):
File "C:\Users\Me\Desktop\My Programs\Feels Bot\Feels Bot\FeelsBot.py", line 18, in <module>
has_feels = 'feels' in comment
TypeError: argument of type 'Comment' is not iterable
sys:1: ResourceWarning: unclosed <socket object at 0x0369D8E8>
C:\Python34\lib\importlib\_bootstrap.py:2150: ImportWarning: sys.meta_path is empty
有没有人知道怎么解决这个问题,让它能够检查评论中是否包含“feels”,如果有的话就把has_feels设置为true?
另外,一旦它查看完一个帖子的所有评论,就会停止,不会继续查看下一个帖子。有没有人知道怎么解决这个问题?如果你不确定,不用特意去查,我可以自己找出这个部分。
1 个回答
7
has_feels = 'feels' in comment
这里的comment
看起来是一个对象,它有一些属性,而这些属性本身是不能像list
(列表)或string
(字符串)那样被逐个遍历的。
根据praw的文档,你需要通过body
属性来访问评论的内容:
所以你可以这样做:
has_feels = 'feels' in comment.body
这里有一些例子,说明你现在的做法为什么不奏效:
>>> "x" in "xxyy" # works (string is iterable)
>>> "x" in ["x", "y"] # works (list is iterable)
>>> class MyClass(): pass
>>> c = MyClass()
>>> "y" in c
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'instance' is not iterable