python读取dbc文件

python读取dbc文件

方案一:

import os
import re
import copy
import json

class DBC:
    def __init__(self):
        self.dbc_json = {}
        self.bus = {}
        self.signals = {}
        self.node = {}
        filePath = "文件"
        if filePath:
            # print(filePath)
            with open(filePath, "r") as f:  # 打开文件
                self.data = f.read()  # 读取文件
                # print(data)

    def read_bus(self):
        read_bus = re.findall("BO_ (.+?):", self.data)
        # print(read_bus)
        print(read_bus)
        for bus in read_bus:
            bus = str(bus).split()
            print(bus[1])
            dick = {"bus": bus[1]}
            self.dbc_json.update(dick)
        return self.dbc_json

    def read_signals(self):
        signal = re.findall("SG_ (.+?):", self.data)
        for sig in signal:
            i = str(sig).split()
            if len(i) == 1:
                self.signals = {"signal": i[0]}
                print(self.signals)
            else:
                pass

    def read_nodes(self):
        pattern = re.compile(r"BO_ (.*?) (.*?): (.*?) (.*)")
        nodes = re.findall(pattern, self.data)
        node_list = []
        for node in nodes:
            #  ('788', 'CCU_01', '8', 'CGW')
            node_list.append(node[3])
        print(set(node_list))
        return set(node_list)

    def bdc_dick(self):
        for i in self.read_nodes():
            dick_i = {i: []}
            self.dbc_json.update(dick_i)
        print(self.dbc_json)
        for a in self.read_bus():
            dick_a = {a: []}
            self.dbc_json.update()


if __name__ == '__main__':
    dbc = DBC()
    print(dbc.read_signals())

方案二:

import re
import copy

node = []
allDatas = []
siganlList = []
SignalsName = []
messageName = []


def readFile():
    """
    用于解析.dbc
    :return:
    """
    global node, allDatas, siganlList, SignalsName, messageName
    ''' 得到dbc文件的绝对路径'''
    # filePath = find_file()
    filePath = "文件名"
    if filePath:
        print(filePath)
        f = open(filePath, "r")  # 设置文件对象
    else:
        print("读取文件失败!")
        return 0
    """
    NodesPattern:节点
    MessagePattern:消息
    SignalPattern:信号
    """
    NodesPattern = re.compile(r"BU_: (.*)", re.S)
    MessagePattern = re.compile(r"BO_ (.*?) (.*?): (.*?) (.*)", re.S)
    SignalPattern = re.compile('''SG_ (.*?) : (.*?)\|(.*?)@.*? \((.*?),(.*?)\) \[(.*?)\|(.*?)\] "(.*?)" (.*)''', re.S)
    DefaultValue = '''BA_ "GenSig(.*?)" SG_ (\d+) signalname (\d+);'''

    line = f.readline()
    allDatas = []
    while line:
        """ 匹配出节点 """
        NodesSearched = re.search(NodesPattern, line.strip())
        if NodesSearched:
            node = NodesSearched.group(1).split(" ")
            # print(node)
        """ 匹配出消息 """
        MessageSearched = re.search(MessagePattern, line.strip())
        if MessageSearched:
            siganlList.clear()
            """如果匹配到了message,则获取到message的相关参数 
             比如匹配到了NM_Message_ESC_409,则会解析出改message的一些参数构成list对象['1033', 'NM_Message_ESC_409', '8', 'ESC']
             这四个参数分别是 messgage ID ;message name ; messgae dataLenth ,message sender
             而且把这个list对象 加在了 siganlList 索引0的位置
            """
            Message = list(MessageSearched.groups())
            siganlList.append(Message)
            """ 只 要 message的名字 messageName 列表中"""
            messageName.append(Message[1])
            """读取下一行"""
            line = f.readline()
            """因为有些message并没有定义signal,所以 下一行还是message"""
            MessageSearched = re.search(MessagePattern, line.strip())
            SignalSearched = re.search(SignalPattern, line.strip())
            """下一行如果不是message的内容 就一定是signal的内容了"""
            if not MessageSearched:
                while SignalSearched:
                    """获取信号的参数追加到siganlList"""
                    signal = list(SignalSearched.groups())
                    siganlList.append(signal)
                    """只获取 signal name"""
                    SignalsName.append(signal[0])

                    # 再次解析信号,直到这个message下的信号全部解析完毕
                    line = f.readline()
                    SignalSearched = re.search(SignalPattern, line.strip())
            # print(siganlList)
            c = copy.deepcopy(siganlList)
            allDatas.append(c)
        else:
            line = f.readline()
            MessageSearched = re.search(MessagePattern, line.strip())
    f.close()  # 将文件关闭
    return 1


def find_file():
    import os
    path = os.path.abspath('.')
    dirs = os.listdir(path)  # 获取指定路径下的文件
    for i in dirs:
        if os.path.splitext(i)[1] == ".dbc":
            return os.path.join(path, i)


if __name__ == '__main__':
    readFile()
    # print(node)
    # print(messageName)
    # print(SignalsName)
    print(type(SignalsName))
    # print(allDatas)

你可能感兴趣的:(python,windows,开发语言)