文本解析 python 多行,关于python:基于文本的数据格式,支持多行字符串

我搜索支持多行字符串的基于文本的数据格式。

JSON不允许多行字符串:

>>> import json

>>> json.dumps(dict(text='first line

second line'))

'{"text":"first line\

second line"}'

我想要的输出:

{"text":"first line

second line"}

这个问题是关于输入和输出的。 数据格式应该可以使用vi,emacs或notepad等编辑器进行编辑。

我不在乎是否使用简单的引号"或tripple引号(如在Python中)"""。

是否有一个易于人类可读的文本数据交换格式支持这个?

用例

我想用多行字符串vi编辑数据。 如果数据是json格式,这不好玩。

你能详细说明数据格式/目的,即复杂的结构或一些设置/配置文件等。

@NabeelAhmed我想用它进行配置。 许多应用程序发明了自己的配置语言。 我想避免这种情况。 但是json和ConfigParser并不满足我。 Json不允许带换行符的字符串(仅 n)和ConfigParser不允许嵌套数据结构。 我缺少的下一件事:验证(但这是一个不同的主题)。 亲爱的Nabeel,如果有遗漏,请留下新评论。

我想如果你可以替换转储结果,那么结果应该是正确的。data = json.dumps(dict(text='first line

second line')) data = data.replace('\

', '

') print(data)

我认为你应该考虑YAML格式。它支持块表示法,它能够保留这样的换行符

data: |

There once was a short man from Ealing

Who got on a bus to Darjeeling

It said on the door

"Please don't spit on the floor"

So he carefully spat on the ceiling

对于任何类型的编程语言都有很多解析器,包括python(即pyYaml)。

还有一个巨大的优势,任何有效的JSON都是YAML。

赞成为打油诗。

你评论的答案:

I want to use it for configuration. A lot of applications invent

their own configuration language. I want to avoid this. But json and

ConfigParser don't satisfy me. Json does not allow strings with

newlines (only

) and ConfigParser does not allow nested data

structures. Next thing that I am missing: Validation (But this is a

different topic).

ConfigParser,ConfigObj或YAML(PyYAML)有3个主要选项 - 每个选项都有其特定的优点和缺点。对于您的用例即配置文件,所有3个优于JSON。

现在进一步说,哪一个更好取决于你想要在conf文件中存储什么。

ConfigObj - 用于配置和验证(您的用例):

ConfigObj非常简单,然后使用YAML(也就是ConfigParser)。支持默认值和类型,还包括验证(优于ConfigParser)。

ConfigObj简介

When you perform validation, each of the members in your specification

are checked and they undergo a process that converts the values into

the specified type. Missing values that have defaults will be filled

in, and validation returns either True to indicate success or a

dictionary with members that failed validation. The individual checks

and conversions are performed by functions, and adding your own check

function is very easy.

附:是的,它允许多行值。

有用的网址:

一个简短的ConfigObj教程

ConfigObj 5简介和参考

在比较YAML与ConfigParser和ConfigObj之间有可靠的SO答案:

什么更好,ConfigObj或ConfigParser?

ConfigObj / ConfigParser与使用YAML for Python设置文件

如果你对标记开销没问题,可以使用ElementTree(标准库)或lxml的XML:

数据

Lorem

Ipsum

Dolor

脚本

import xml.etree.ElementTree

root = xml.etree.ElementTree.parse('data.xml').getroot()

for child in root:

print(child.tag, child.attrib, child.text)

产量

string {} Lorem

Ipsum

Dolor

如果文件仅由Python使用(忽略交换),您可以简单地将数据放在python脚本文件中并将其作为模块导入:

数据

datum_1 =""" lorem

ipsum

dolor

"""

datum_list = [1,"""two

liner"""]

datum_dict = {"key": None,"another": [None, 42.13]}

datum_tuple = ("anything","goes")

脚本

from data import *

d = [e for e in locals() if not e.startswith("__")]

print( d )

for k in d:

print( k, locals()[k] )

产量

['datum_list', 'datum_1', 'datum_dict', 'datum_tuple']

datum_list [1, 'two

liner']

datum_1  lorem

ipsum

dolor

datum_dict {'another': [None, 42.13], 'key': None}

datum_tuple ('anything', 'goes')

更新:

代码与字典理解

from data import *

d = {e:globals()[e] for e in globals() if not e.startswith("__")}

for k in d:

print( k, d[k] )

ini格式也支持多行字符串; Python stdlib中的configparser可以处理它。请参阅https://docs.python.org/3/library/configparser.html#supported-ini-file-structure。

如果您使用的是Python 2,我实际上认为json可以满足您的需求。您可以在解码和加载json时使用string-escape对其进行解码和编码:

import json

config_dict = {

'text': 'first line

second line',

}

config_str = json.dumps(config_dict).decode('string-escape')

print config_str

config_dict = json.loads(config_str.encode('string-escape'))

print config_dict

输出:

{"text":"first line

second line"}

{u'text': u'first line

second line'}

因此,您可以使用解码后的字符串来编辑JSON,包含换行符,并在读取时,只需使用string-escape进行编码即可获取字典。

不确定我是否正确理解了你的问题,但你不是要求这样的事吗?

my_config = {

"text":"""first line

second line"""

}

print my_config

这是什么样的数据格式? 你展示了Python的来源。 这已经是用户"句柄"的答案。

@guettli哦,没错,我的观点与"处理"用户完全相同。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值