首页 > 解决方案 > xlrd 无法找到特殊的 IPv6 值,也无法将 CSV/txt 加载到字典列表中

问题描述

亲爱的,

我真的很难在 .xslx、.csv 或 .txt 中找到特定的 IPv6 地址。可以找到其他地址(至少是我测试过的)。

代码:

def def_load_csv_to_dict(filename: str):
    import csv
    reader = csv.reader(open(filename, 'r'))
    data = []
    for row in reader:
        d = {}
        hostname, vtep = row
        d['hostname'] = hostname
        d['vtep'] = vtep
        data.append(d)
    return data


def def_load_txt_file_to_dict(filename, os_child_dir: str = None):
    import re
    import os
    if os_child_dir is not None:
        os.chdir(os_child_dir)
    data = []
    with open(filename) as f:
        for line in f:
            d = {}
            values = re.search(r'(ipi-\w+-r-(ml|ms|al)-\d+),(\w+:\w+:\w+:\w+:\w+:\w+:\w+:\w+)', line)
            try:
                key1 = 'hostname'
                val1 = values.group(1)
                d[(key1)] = val1

                key2 = 'vtep'
                val2 = values.group(3)
                d[(key2)] = val2

                data.append(d)
            except AttributeError:
                continue
        return data


def def_get_al_hostnames(vtep:str):
    print(f'VTEP we are looking for: {vtep}')
    al_hostnames = []
    for line in (def_load_txt_file_to_dict('all_leaf_vtep_host_mapping.txt')):
        print(line)
        if line['vtep'] == vtep:
            al_hostnames.append(line['hostname'])
    return al_hostnames


print(def_get_al_hostnames('2001:4D98:A100:0:1:750:3:65'))

csv/txt 文件条目如下:

ipi-zhb790-r-al-96,2001:4D98:A100:0:1:790:3:9096
ipi-zhb790-r-al-97,2001:4D98:A100:0:1:790:3:9096

请给谁建议?

标签: pythonexcelcsvxlsx

解决方案


提供def_load_txt_file_to_dict函数的修改版本以使用而不是正则表达式匹配(它与模块加载数据str.split的方式更一致):csv

def def_load_txt_file_to_dict(filename, os_child_dir: str = None):
    import os
    if os_child_dir is not None:
        os.chdir(os_child_dir)
    data = []
    with open(filename) as f:
        for line in f:
            hostname, ipv6 = line.split(",")
            d = {
                "hostname": hostname,
                "vtep": ipv6
            }
            data.append(d)
    return data

推荐阅读