【问题标题】:Convert .csv to .jsonl python将 .csv 转换为 .jsonl python
【发布时间】:2021-07-29 19:38:48
【问题描述】:

我有一个 .csv 文件,我想将其转换为 .jsonl 文件。

我找到了 Pandas to_json 方法:

df = pd.read_csv('DIRECTORY/texts1.csv', sep=';')
df.to_json ('DIRECTORY/texts1.json')

但是,我不知道将其转换为 .jsonl 格式的功能。我该怎么做?

【问题讨论】:

  • 什么是.jsonl?没有这样的标准或文件格式。有很多尝试劫持将未缩进的 JSON 文档存储在单独的行中的常见做法,这只是 不是 任何类型的标准 - 您只需将未缩进的 JSON 字符串附加到末尾一个文件
  • 正如我所说,a lot of attempts to hijack a common practice。只需将 JSON 字符串附加到所需文件的末尾即可。这就是重点。您只需要读取到下一个换行符即可读取 JSON 文档,而不是读取整个文件。
  • 事实上,ndjson.org 出现在 jsonlines.org 之前,并且包含与历史上的 json.org 站点相同的文本,与 Douglas Crockford 或 ECMA 没有任何关系
  • this answer可以看到to_json如果使用orient='records', lines=True,可以将每一行写在单独的行中。来自to_json docsIf ‘orient’ is ‘records’ write out line delimited json format. Will throw ValueError if incorrect ‘orient’ since others are not list like.

标签: python json pandas csv data-conversion


【解决方案1】:

我不确定这个结果是否符合“jsonl”语法,但它可能会导致相关结果。

主要技巧是在导出时将输入文件的每一行视为单独的 JSON 文件,然后从磁盘读回该 JSON 并将其视为不同的 jsonl 行。

我从一个包含

的 CSV 开始
hello, from, this, file
another, amazing, line, csv
last, line, of, file

下面的 sn-p 建立在 another post 之上。

import pandas
df = pandas.read_csv("myfile.csv", header=None)

file_to_write = ""
for index in df.index:
    df.loc[index].to_json("row{}.json".format(index))
    with open("row{}.json".format(index)) as file_handle:
        file_content = file_handle.read()
        file_to_write += file_content + "\n"
        
with open("result.jsonl","w") as file_handle:
    file_handle.write(file_to_write)

生成的 .jsonl 文件包含

{"0":"hello","1":" from","2":" this","3":" file"}
{"0":"another","1":" amazing","2":" line","3":" csv"}
{"0":"last","1":" line","2":" of","3":" file"}

如果不需要行索引,可以从上面 Python sn-p 的 .to_json() 行中删除。

【讨论】:

    猜你喜欢
    • 2021-08-21
    • 2016-05-14
    • 2021-08-24
    • 1970-01-01
    • 2021-07-05
    • 2021-08-23
    • 1970-01-01
    • 2021-07-23
    • 2016-12-19
    相关资源
    最近更新 更多