在Python中将字符串拆分为字典

2024-04-26 01:16:19 发布

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

我想把这个字符串拆分成字典。字符串是使用

$ sudo btmgmt find |grep rssi |sort -n |uniq -w 33

我的结果是

hci0 dev_found: 40:43:42:B3:71:11 type LE Random rssi -53 flags 0x0000 
hci0 dev_found: 44:DA:5F:EA:C6:CF type LE Random rssi -78 flags 0x0000

目标是创建字典,其中key是MAC地址,value是rssi值

dict = {
    "40:43:42:B3:71:11": "-53 ",
    "44:DA:5F:EA:C6:CF": "-78",
   }

我尝试了很多replace函数来将这些字符串替换为空字符串:

  • 发现hci0设备:
  • 类型
  • 随机的
  • rssi公司

但它必须更干净,更好的方式做这本字典,我不认为这个解决办法。你知道吗

有什么想法吗?你知道吗


Tags: 字符串devle字典typerandomdacf
3条回答

如果每行具有相同的结构,则可以使用split()将文本拆分为行,然后使用split()将每行拆分为“单词”,您可以使用这些单词在字典中创建元素:

s = """
hci0 dev_found: 40:43:42:B3:71:11 type LE Random rssi -53 flags 0x0000 
hci0 dev_found: 44:DA:5F:EA:C6:CF type LE Random rssi -78 flags 0x0000
"""

d = dict()

for line in s.split('\n'):
    line = line.strip() # clear spaces and enters
    if line: # skip empty lines
        words = line.split(' ')
        d[words[2]] = words[7]

print(d)        

由于列之间用空格分隔,因此可以使用split方法:

s = """hci0 dev_found: 40:43:42:B3:71:11 type LE Random rssi -53 flags 0x0000 
hci0 dev_found: 44:DA:5F:EA:C6:CF type LE Random rssi -78 flags 0x0000"""

sdic = {}

for line in s.split('\n'):
    column = line.split(' ')
    sdic[column[2]] = column[7]

print(sdic)

可以将re.findall与regex lookaheads和lookbehinds一起使用:

import re
s = """
hci0 dev_found: 40:43:42:B3:71:11 type LE Random rssi -53 flags 0x0000 
hci0 dev_found: 44:DA:5F:EA:C6:CF type LE Random rssi -78 flags 0x0000
"""
d = dict([re.findall('(?<=dev_found:\s)[A-Z\d:]+|[\-\d]+(?=\sflags)', i) for i in filter(None, s.split('\n'))])

输出:

{'40:43:42:B3:71:11': '-53', '44:DA:5F:EA:C6:CF': '-78'}

相关问题 更多 >