【发布时间】:2020-01-04 15:17:21
【问题描述】:
我正在尝试使用 Reddit 线程的 cmets 作为机器学习程序的训练集。 https://old.reddit.com/r/bayarea/comments/cxxl9y/billionaires_yacht_docked_in_embarcadero.json 是一个输入示例。
我正在过滤掉 body、id 和 parent_id,希望将嵌套的 JSON 变成许多对话。
例如,如果输入为["A", ["B",["C", "D"]]],则输出应为["A", "B", "C"], ["A","B","D"]。
以下是我当前的代码:
json_url = "https://old.reddit.com/r/bayarea/comments/cxxl9y/billionaires_yacht_docked_in_embarcadero.json"
r = requests.get(json_url, headers={"user-agent": "PostmanRuntime/7.15.2"})
comments_tree_raw = fltr(r.json(), ["ups", "body", "id", "parent_id"])[1]["data"]
comments_tree_raw = flatten([], comments_tree_raw["children"])
def remove_all_after(node, index):
target = node.index(index)
return node[:target]
training_threads = []
# input the children list
def flatten(output, children):
global training_threads
for child in children:
try:
child_obj = child["data"] if "body" in child["data"] else child
child_comment = {
"body": child_obj["body"],
"id": child_obj["id"],
"parent": child_obj["parent_id"]
}
output.append(child_comment)
except KeyError:
continue
if "replies" not in child["data"]:
training_threads.append(output.copy())
parent_id = child_comment["parent"].split("_")[1]
for i in output:
if i["id"] == parent_id:
output = remove_all_after(output, i)
break
continue
flatten(output, child["data"]["replies"]["data"]["children"])
在这里,我试图递归地解决问题,但它没有产生我需要的输出。这是我得到的输出:https://pastebin.com/GkpwGUtK。
非常感谢您的帮助!谢谢!
【问题讨论】:
标签: python list recursion reddit flatten