我有一个.csv文件,我想把它转换成一个.jsonl文件。
我找到了Pandas to_json
方法:
df = pd.read_csv('DIRECTORY/texts1.csv', sep=';')
df.to_json ('DIRECTORY/texts1.json')
但是,我不知道有一个函数可以将它转换为.jsonl格式。我该怎么做?
发布于 2021-05-09 18:13:25
我不确定这个结果是否符合"jsonl“语法,但这是一个可能导致相关结果的攻击。
主要技巧是在导出时将输入文件的每一行视为单独的JSON文件,然后从磁盘中读取该JSON,并将其视为不同的jsonl行。
我从CSV开始
hello, from, this, file
another, amazing, line, csv
last, line, of, file
下面的代码片段构建在另一个职位上。
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"}
如果不需要行索引,可以从上面代码段的.to_json()行中删除这些索引。
发布于 2022-04-22 17:40:45
这可能有点晚了,但我编写了一个名为朱诺的愚蠢模块,它可能有助于解决这类问题。
>>> from csv_jsonl import JSONLinesDictWriter
>>> l = [{"foo": "bar", "bat": 1}, {"foo": "bar", "bat": 2}]
>>> with open("foo.jsonl", "w", encoding="utf-8") as _fh:
... writer = JSONLinesDictWriter(_fh)
... writer.writerows(l)
...
它扩展了本机csv
模块,因此它非常熟悉。希望能帮上忙。
https://stackoverflow.com/questions/67435906
复制相似问题