将Python中的字典解析到当前表中

问题描述 投票:0回答:1

我有一个包含几个类别的表,其中两个是:mac地址和设备名称。我有一个用我的代码(硬编码)写的我的mac地址列表及其相应的设备名称(即deviceDict['00:00:00:00:00:00']= name

现在,我将这些mac地址和设备名称传递到一个文本文件,以从相同的Python代码读取该文件并将其解析到我的表中。该代码当前可识别文本文件,但未将信息解析到表上。

这里是代码:

# File: WapLogParser.py
# Desc: Parses a WAP log file and pulls out information relating to connected clients
# Usage: python WapLogParser.py [file glob]

import re
import sys
import glob
import os

deviceDict = dict()

# Base table for storing client info
# All names must match what is in the Wap Log file
#   Exceptions: Date, Wap Name, Device Name - which are provided outside of the result parsing
table = [["Ssid", "Vlan", "Mac Address", "Connected Time", "Ip Address", "Rssi", "Date", "Wap Name", "Device Name"]]

def ParseResult(result, date, wapName):
    lines = result.split('\n')
    lines = list(filter(None, lines))
    # Any useful info will be at least 2 lines long
    if len(lines) == 1:
        return
    # create empty row
    data = [""] * len(table[0])
    # for each item in the result place it in the correct spot in the row 
    for line in lines:
        if line != "":
            # Parse the key/value pair
            m = re.match(r"(.*):\s\.*\s?(.*)", line)
            if m is not None:
                for idx in range(len(table[0])):
                    if table[0][idx].lower() == m[1].lower():
                         data[idx] = m[2]
        else:
            break

    # Remove the '(dBm)' from the RSSI value
    data[5] = data[5].split()[0]

    # Append WAP specific items to row
    data[6] = date
    data[7] = wapName
    data[8] = GetDeviceName(data[2].upper())

    # Add row to table
    table.append(data)


def ParseFile(path):
    with open(path) as f:
        lines = f.readlines()
        result = ""
        command = ""
        date = ""
        # WAP name is always on the first line 16 characters in with 4 
        # unnecessary characters trailing
        wapName = lines[0].strip()[16:-4]
        for line in lines:
            line = line.strip()
            # Is an issued command?
            if line.startswith("/#"):
                if command != "":
                    ParseResult(result, date, wapName) 
                command = "" 
                # reset the result for the new command
                result = ""
                m = re.match(r"^/#.*show\sclient.*stats$", line)
                if m is not None:
                    command = line
            # Anything that is not a command add to the result
            else:
                result += line + "\n"

            # Do we have the date?
            if line.startswith("Current date:"):
                date = line.replace("Current date: ", "")

# Print output to stderr
def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

# Print a 2d array in a csv format
def PrintAsCsv(table):
    for row in table:
        print(",".join(row))


def Main():
    InitDeviceDict()
    numArgs = len(sys.argv)
    for filename in glob.iglob(sys.argv[numArgs - 1], recursive=True):
        # Globs get directories too
        if os.path.isfile(filename):
            eprint("Parsing " + filename)
            try:
                ParseFile(filename)
            except Exception as e: # Mainly for if we see a binary file
                eprint("Bad file: " + e)

    # Print in a format we can use
    PrintAsCsv(table)


def GetDeviceName(macAddress):
    if macAddress in deviceDict:
        return deviceDict[macAddress]

    manufacturerPart = macAddress[:8]
    if manufacturerPart in deviceDict:
        return deviceDict[manufacturerPart]

    return 'Unknown Device'


def InitDeviceDict():
    with open('try.txt','r') as fo:
        for line in fo:
           deviceDict = {}
           line = line.split(',')
           macAddress = line[0].strip()
           manufacturerPart = line[1].strip()
           if macAddress in deviceDict:
               deviceDict[macAddress].append(manufacturerPart)
           else:
               deviceDict[macAddress]=(manufacturerPart)


           print(deviceDict)

# entry point
# script arguments:
#   WapLogParser.py [file glob]
if __name__ == "__main__":
    Main()

问题出在函数GetDeviceName和InitDeviceDict上。当我运行代码,然后运行一个批处理文件以在excel上显示我的信息时,我不断收到“未知设备”(好像它无法识别我输入的产生设备名称的mac地址)

可以通过任何方式纠正此问题?谢谢

python text hashtable hashcode
1个回答
0
投票

deviceDict中填充的InitDeviceDict不是全局deviceDict。您只在修改本地函数字典(并在每一行都将其重置)。从该函数中删除deviceDict = {},然后在函数顶部使用global deviceDict声明您正在修改全局。

def InitDeviceDict():
    global deviceDict
    with open('try.txt','r') as fo:
        for line in fo:
           line = line.split(',')
           macAddress = line[0].strip()
           manufacturerPart = line[1].strip()
           if macAddress in deviceDict:
               deviceDict[macAddress].append(manufacturerPart)
           else:
               deviceDict[macAddress]=[manufacturerPart]
© www.soinside.com 2019 - 2024. All rights reserved.