python - 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
请给谁建议?
解决方案
提供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
推荐阅读
- security - 如何在 suricata.yml 的 HOME_NET 中定义几个地址?
- c# - 列表未设置值到演示者的控件
- javascript - 使用 pdf.js 在带有加载的 pdf 文件的画布中绘制矩形
- java - 如果客户端在密钥库中有多个证书,将选择哪个 SSL 证书
- kubernetes - Kubenetes Pod 显示状态“已完成”,没有任何作业
- excel - VBA随机函数问题 - 关闭工作文件时不起作用
- java - 如何在 Liferay 7.2 中使用 DynamicQuery 查询 JournalArticle 的最新版本
- javascript - ${} 模板文字(ES2015)在 jsp 页面下工作
- r - 将闪避和堆栈位置与 ggplot2 组合在同一个条形图中
- regex - 正则表达式中的顺序不重要吗?