【发布时间】:2022-01-07 17:23:47
【问题描述】:
尝试从给定的字符串创建字典,可以是格式
key1:value1 key2:value2
但是有时选择价值是个问题
- 空格
key1: value1 - 引用
key1: "value has space"
密钥的标识符是something:
在下面尝试过
def tokenize(msg):
legit_args = [i for i in msg if ":" in i]
print(legit_args)
dline = dict(item.split(":") for item in legit_args)
return dline
以上仅适用于无空格值。
然后在下面尝试
def tokenize2(msg):
try:
#return {k: v for k, v in re.findall(r'(?=\S|^)(.+?): (\S+)', msg)}
return dict(token.split(':') for token in shlex.split(msg))
except:
return {}
这适用于key:"something given like this",但仍需要一些更改才能工作,以下是问题
>>> msg = 'key1: "this is value1 " key2:this is value2 key3: this is value3'
>>> import shlex
>>> dict(token.split(':') for token in shlex.split(msg))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #1 has length 1; 2 is required
>>> shlex.split(msg) # problem is here i think
['key1:', 'this is value1 ', 'key2:this', 'is', 'value2', 'key3:', 'this', 'is', 'value3']
【问题讨论】:
-
什么是完整字符串示例?
-
第二种(正则表达式)方法到底有什么问题?示例输入和输出会有所帮助
-
题外话,但a bare
exceptis bad practice。相反,请使用您期望的特定异常,例如except ValueError,或至少except Exception。 -
添加了更多细节@KeoniGarner,我认为这很好,因为有空格的值应该只用引号括起来
-
值是否可以在引号内包含冒号?