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

3

我想将字符串拆分为字典。该字符串是通过使用

$ 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

目标是创建一个字典,其中键是MAC地址,值是rssi值。
dict = {
    "40:43:42:B3:71:11": "-53 ",
    "44:DA:5F:EA:C6:CF": "-78",
   }

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

  • hci0 dev_found:
  • type
  • LE
  • Random
  • rssi

但肯定有更好的方法来处理这个字典,只是我并没有看到这种解决方案。

有什么想法吗?


如果每一行都有相同的结构,那么你可以将该行使用split(" ")分割成列表中的元素,并使用列表中的元素来创建字典中的元素。 - furas
4个回答

2
如果每一行的结构都相同,那么您可以使用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)        

0
你可以使用 re.findall 与正则表达式的预测先行断言和后发断言:
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'}

0
因为列是由空格分隔的,所以您可以使用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)

0

输入:给定行的文件

import re
d = dict()
c1 = re.compile("((\d|\w){1,2}:){5}(\d|\w){1,2}")
c2 = re.compile(r"(-\d{2}) flags")
with open("your_saved_lines.txt") as fh:
  for l in fh.readlines():
    m1 = c1.search(l)
    m2 = c2.search(l) or "NA"
    if m1:
      d[m1.group()] = m2.group(1)
print(d)

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接