文本解析 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哦,沒錯,我的觀點與"處理"用戶完全相同。
總結
以上是生活随笔為你收集整理的文本解析 python 多行,关于python:基于文本的数据格式,支持多行字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 添加日志_第五章springboot2.
- 下一篇: php查询变量类型,php判断变量类型常