gpt4 book ai didi

python - 我的 Python 正则表达式代码没有给出我预期的输出

转载 作者:行者123 更新时间:2023-12-01 01:55:49 24 4
gpt4 key购买 nike

我试图从文本文件中提取并解析单词(主机名和版本)。当我运行代码时,它将数据写入 csv 文件,但输出看起来不同。 output i had after parsing to csv

 **my input file is .txt and below is the content** 
Hostname Router1
version 15.01
code:
line console 0
logging synchronous
exec-timeout 15 1
usb-inactivity-timeout 15
exec prompt timestamp
transport preferred none

Hostname Router2
version 15.02
line vty 0 15
logging synchronous
exec-timeout 15 2
exec prompt timestamp
transport input ssh
transport preferred none
access-class REMOTE_ACCESS in

Hostname Router3
version 15
line console 0
logging synchronous
exec-timeout 15 3
usb-inactivity-timeout 15
exec prompt timestamp
transport preferred none

Hostname Router3
version 15.12
line vty 0 15
logging synchronous
exec-timeout 15 4
exec prompt timestamp
transport input ssh
transport preferred none
access-class REMOTE_ACCESS in
**Above is the sample content in my input text file**
$
import re
import csv
with open('sample5.csv','w',newline='') as output:
HeaderFields = ['Hostname','version']
writer = csv.DictWriter(output,fieldnames=HeaderFields)
writer.writeheader()
with open('testfile.txt','r',encoding='utf-8') as input:
for line in input.readlines():
pattern = re.compile(r'Hostname(.*)''|''version(.*)')
match=pattern.finditer(line)
for match1 in match:
with open('sample5.csv', 'a',newline='') as output:
writer = csv.DictWriter(output, fieldnames=HeaderFields)
writer.writerow({'Hostname': match1.group(1), 'version':
match1.group(2)})

我的 csv 预期结果如下: This should be the result in csv

谢谢。

最佳答案

您的代码失败,因为在每次迭代中您只读取一行(可以包含主机或版本,但不能同时包含两者,但您将数据写入 csv。让我们在匹配双线时迭代所有文本:第一行主机名.. 第二行版本...\n 作为 Windows 的换行符(我听说 Mac 使用\r 不确定)。现在,由于您匹配了双线,您可以从同一匹配对象中获取路由器和版本。

with open('testfile.txt','r',encoding='utf-8') as input:
txt = input.read()
pattern = re.compile(r'Hostname (.*)(\r\n?|\n)version (.*)')
match=pattern.finditer(txt)
for match1 in match:
with open('sample5.csv', 'a',newline='') as output:
writer = csv.DictWriter(output, fieldnames=HeaderFields)
writer.writerow({'Hostname': match1.group(1), 'version':
match1.group(3)})

关于python - 我的 Python 正则表达式代码没有给出我预期的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50205977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com