[英]split comma-separated key-value pairs with commas
有點像這個問題: 如何用逗號分隔逗號分隔的鍵值對
但我的問題是:
line='name=zhg,code=#123,"text=hello,boy"'
注意,“ text = hello,boy”,不是:text =“ hello,boy”
我想把這條線分開來。 我想要的輸出是:
"name":"zhg","code":"#123","text":"hello,boy"
如何使用正則表達式或shlex獲取它?
您不能使用正則表達式來做到這一點,否則它將不是最有效的。 使用單通道解析器解析此類字符串的代碼很簡單:
line='name=zhg,code=#123,"text=hello,boy"'
def read_quote(string):
out = ''
for index, char in enumerate(string):
if char == '"':
index += 2 # skip quote and comma if any
return index, out
else:
out += char
def read(string):
print('input', string)
out = ''
for index, char in enumerate(string):
if char == ',':
index += 1 # skip comma
return index, out
else:
out += char
# end of string
return index, out
def components(string):
index = 0
while index < len(line):
if string[index] == '"':
inc, out = read_quote(string[index+1:])
index += inc
yield out
else:
inc, out = read(string[index:])
index += inc
yield out
print(dict([e.split('=') for e in components(line)]))
它打印以下內容:
{'text': 'hello,boy', 'code': '#123', 'name': 'zhg'}
如果確實需要,可以使用正則表達式實現read
和read_quote
。
您可以將csv.reader
與適當的“類似於文件的”字符串一起使用。
>>> import csv
>>> import StringIO
>>> line='name=zhg,code=#123,"text=hello,boy"'
>>> string_file = StringIO.StringIO(line)
>>> for row in csv.reader(string_file):
... print row
...
['name=zhg', 'code=#123', 'text=hello,boy']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.