按换行符参数“\n”拆分Python dict数据

2024-09-30 14:20:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有使用javascript通过POST获得的dict数据。dict数据保存在变量“commands”中,commands中的数据如下所示:

{flightplantext': 'TAKEOFF\r\nUP 80\r\nDOWN 80\r\nLAND'}

我想用python以以下格式将此数据存储在新的dict/列表中:

{'takeoff', 'up_80', 'down_80', 'land'}

基本上,我希望将每个命令按\r\n部分拆分,使其小写,如果命令和数字之间有空格,则使用下划线

我对Python非常陌生,非常感谢。提前非常感谢


Tags: 数据命令列表格式javascriptpostdictcommands
3条回答

如果您可以从javascript中获取的数据中提取字符串

data = commands.get('flightplantext') # data = 'TAKEOFF\r\nUP 80\r\nDOWN 80\r\nLAND'

因此data将是如下所述的字符串

'TAKEOFF\r\nUP 80\r\nDOWN 80\r\nLAND'.lower().replace(" ","_").split("\r\n")

输出将是

['takeoff', 'up_80', 'down_80', 'land']

使用带有列表理解的re.findall生成字典,我们可以尝试:

inp = 'TAKEOFF\r\nUP 80\r\nDOWN 80\r\nLAND'
output = re.findall(r'(.*?)\r\n(.*?)(?:\r\n|$)', inp)
output = [[y.lower().replace(" ", "_") for y in x] for x in output]
d = dict(output)
print(d)  # {'down_80': 'land', 'takeoff': 'up_80'}

假设您的commands变量是dict,这就是您要查找的:

raw = commands["flightplantext"]                 # Get the value
parts = [p.lower() for p in raw.split("\r\n")]   # Split it
# Convert to dict
final = dict(zip(parts[::2], [i.replace(" ", "_") for i in parts[1::2]]))

相关问题 更多 >