知道如何将其读取为 CSV 吗? - Python

发布于 2024-10-13 00:49:43 字数 342 浏览 1 评论 0原文

我有一个 CSV 文件,其格式如下:

ID=123[DLE]KEY=测试[DLE]KEY2=VAL123

其中 [DLE] 是 "数据链接escape”控制字符


知道如何将其与 csv 标准库一起使用吗?

我是否需要编辑每一行以使其兼容?

编辑:我的主要问题是“KEY=VALUE”格式

谢谢大家

I have a CSV formatted in the following way:

ID=123[DLE]KEY=test[DLE]KEY2=VAL123

where [DLE] is the "Data link escape" control character


Any idea how I could use this with the csv standard library?

Do I need to edit each row in order to make it compatible?

Edit: my main problem is the "KEY=VALUE" formatting

Thanks guys

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

林空鹿饮溪 2024-10-20 00:49:43

您的数据实际上不是 CSV 格式,所以我会放弃尝试使用它。我要做的就是编写一个生成器,它获取每一行,执行 .split('\x10'),然后执行 .split('=', 1)每一部分,然后将整个内容作为字典生成。

def dgen(fin):
  for line in fin:
    yield dict(((k, v) for chunk in line.rstrip('\r\n').split('\x10')
        for (k, v) in chunk.split('=', 1)))

Your data is not actually in CSV format, so I'd give up on trying to use it. What I'd do is write a generator that took each line, did .split('\x10'), and then did .split('=', 1) on each piece, and then yielded the whole thing as a dict.

def dgen(fin):
  for line in fin:
    yield dict(((k, v) for chunk in line.rstrip('\r\n').split('\x10')
        for (k, v) in chunk.split('=', 1)))
筑梦 2024-10-20 00:49:43

您可以通过简单地覆盖分隔符来解析它(假设雪人是您的 DLE):

import csv
testdata='ID=123☃KEY=test☃KEY2=VAL123\nID=456☃KEY=test2☃KEY2=val456'
testdataiter=testdata.splitlines()
reader = csv.reader(testdataiter, delimiter='☃')
for row in reader:
    print (','.join(row))

输出:

ID=123,KEY=test,KEY2=VAL123
ID=456,KEY=test2,KEY2=val456

检查 csv 模块的帮助 - 任何方言参数都可以在阅读器构造函数中覆盖。


要将 KEY=VAL 解析为字典,请更改为:

...
for row in reader:
    rowdict = dict([x.split('=',1) for x in row])
    print rowdict

输出:

{'KEY2': 'VAL123', 'ID': '123', 'KEY': 'test'}
{'KEY2': 'val456', 'ID': '456', 'KEY': 'test2'}

You can parse it by simply overriding the delimiter (pretend the snowman is your DLE):

import csv
testdata='ID=123☃KEY=test☃KEY2=VAL123\nID=456☃KEY=test2☃KEY2=val456'
testdataiter=testdata.splitlines()
reader = csv.reader(testdataiter, delimiter='☃')
for row in reader:
    print (','.join(row))

outputs:

ID=123,KEY=test,KEY2=VAL123
ID=456,KEY=test2,KEY2=val456

Check the help for the csv module - any of the dialect parameters can be overriden in the reader constructor.


To parse your KEY=VAL into a dict, change to:

...
for row in reader:
    rowdict = dict([x.split('=',1) for x in row])
    print rowdict

outputs:

{'KEY2': 'VAL123', 'ID': '123', 'KEY': 'test'}
{'KEY2': 'val456', 'ID': '456', 'KEY': 'test2'}
冬天旳寂寞 2024-10-20 00:49:43

在 Python 中,您可以向 csv 模块传递格式字符 ( csv 模块文档):

>>> import csv
>>> spamReader = csv.reader(open('eggs.csv', 'rb'), delimiter=' ', quotechar='|')

In Python you can pass the csv module a format character (csv module docs):

>>> import csv
>>> spamReader = csv.reader(open('eggs.csv', 'rb'), delimiter=' ', quotechar='|')
情感失落者 2024-10-20 00:49:43

这就是你所追求的吗?

>>> fields = ["ID","KEY","KEY2"]
>>> mydict = csv.DictReader(open("csv.txt","rbU"),delimiter=chr(16),fieldnames=field
s)
>>> mylist = [line for line in mydict]
>>> mylist
[{'KEY2': 'KEY2=VAL123', 'ID': 'ID=123', 'KEY': 'KEY=test'}]

编辑:上面给出了更好的答案

Is this what you're after?

>>> fields = ["ID","KEY","KEY2"]
>>> mydict = csv.DictReader(open("csv.txt","rbU"),delimiter=chr(16),fieldnames=field
s)
>>> mylist = [line for line in mydict]
>>> mylist
[{'KEY2': 'KEY2=VAL123', 'ID': 'ID=123', 'KEY': 'KEY=test'}]

Edit: Better answer given above

人疚 2024-10-20 00:49:43
reader = csv.reader(open(datafile, "rb"), delimiter=chr(16))
data = (dict(tuple(i.split("=") for i in row)) for row in reader)

会给你一个发电机。您可以将其转换为列表或元组。

data_list = list(data)

这将是一个字典列表。

[{'ID': '123', 'KEY': 'test', 'KEY2': 'VAL123'},
 {'ID': '456', 'KEY': 'test2', 'KEY2': 'val456'}]
reader = csv.reader(open(datafile, "rb"), delimiter=chr(16))
data = (dict(tuple(i.split("=") for i in row)) for row in reader)

Will give you a generator. You can turn it into a list or a tuple.

data_list = list(data)

Which would be a list of dicts.

[{'ID': '123', 'KEY': 'test', 'KEY2': 'VAL123'},
 {'ID': '456', 'KEY': 'test2', 'KEY2': 'val456'}]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文