Python+ScratchAttach:检测数组对象指定键值及获取其他字段方法
解决ScratchAttach消息检查与字段获取问题
步骤1:遍历消息数组并检查内容
直接用Python的for循环遍历你的消息数组,对每条消息用in关键字判断「Hello World」是否在Content字段里:
# 替换成你实际的消息数组变量 messages = [{'CommentID': '317977750', 'User': 'shieldroy', 'Content': 'Can you pls advertise my studio and tell people to comment " generic" on my profile.', 'Timestamp': '2024-03-10T04:47:53Z', 'hasReplies?': False}] # 遍历每条消息 for msg in messages: # 检查Content是否包含目标文本 if 'Hello World' in msg['Content']: # 这里处理匹配到的消息 pass
步骤2:获取匹配消息的其他字段
找到符合条件的消息后,直接通过键名(比如CommentID、User)就能取出对应的值,注意键名要和数组里的完全一致:
# 接上面的代码 for msg in messages: if 'Hello World' in msg['Content']: # 获取各字段值 comment_id = msg['CommentID'] sender_user = msg['User'] send_time = msg['Timestamp'] has_replies = msg['hasReplies?'] # 示例:打印这些值 print(f"匹配到的消息详情:") print(f"评论ID:{comment_id}") print(f"发送用户:{sender_user}") print(f"发送时间:{send_time}") print(f"是否已有回复:{has_replies}")
新手提示
如果担心某些消息里没有指定的键(比如个别消息缺少hasReplies?),可以用msg.get('键名', 默认值)的方式避免报错,比如:
has_replies = msg.get('hasReplies?', False)
这样如果消息里没有这个键,会自动用False作为默认值。
内容的提问来源于stack exchange,提问作者zeeplockd
相关产品推荐
相关产品推荐

