【问题标题】:tqdm progress bar with json string stuck带有json字符串的tqdm进度条卡住了
【发布时间】:2018-08-02 10:36:36
【问题描述】:

我有一个 json 字符串列表,我正在将它们转换为一个字典列表。

我这样做是为了将它们组合成一个最终的 json 字符串,以便稍后转换为 Pandas Dataframe:

s1 = '{ "id": 11, "label": "REF", "claim": "Lorelai Gilmore", "ce": [[[1,2, "Gilmore", 3]]]}'
s2 = '{ "id": 0, "label": "REF", "claim": "named Robert s.", "ce": [[[1,2, "Lorelai", 3]]]}'
s = [s1, s2]

combine = [json.loads(item) for item in s]

r = json.dumps(combine, indent=2)
s = pandas.read_json(r)
print(s)

我的json字符串列表很大,所以我尝试使用Tqdm进度条来监控进度:

combine = tqdm([json.loads(item) for item in s])

但我收到了这个错误:

  0%|          | 0/2 [00:00<?, ?it/s]Traceback (most recent call last):
  File "D:/OneDrive/PhD/fever_challenge/test.py", line 11, in <module>
    r = json.dumps(combine, indent=2)
  File "C:\Python35\lib\json\__init__.py", line 237, in dumps
    **kw).encode(obj)
  File "C:\Python35\lib\json\encoder.py", line 200, in encode
    chunks = list(chunks)
  File "C:\Python35\lib\json\encoder.py", line 436, in _iterencode
    o = _default(o)
  File "C:\Python35\lib\json\encoder.py", line 179, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError:   0%|          | 0/2 [00:00<?, ?it/s] is not JSON serializable

我在跟踪错误时删除了代码中的最后三行,我观察到循环卡住了。这就是我所看到的:

  0%|          | 0/2 [00:00<?, ?it/s]

我的代码有什么问题?

【问题讨论】:

    标签: json python-3.x pandas tqdm


    【解决方案1】:

    试试这个:

    combine = []
    for i in tqdm([json.loads(item) for item in s]):
        combine.append(i)
    

    【讨论】:

    • 感谢它有效,但你为什么这样做(双循环)?!
    • combine = tqdm([json.loads(item) for item in s]) 这里 combine 不是一个列表,而是一个修饰的迭代器 (docs)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多