我对python很新,想要一些帮助。
我有一个名为pdu.tmp的文件,其中包含以下行:
Foldername; PDU-8000;位置:; 172.27.0.69 Foldername; PDU-A8009;位置:; 172.27.0.64 Foldername; PDU-A8091;位置:; 172.27.0.48 ...
我想匹配包含PDU-的行并将它们打印到屏幕上
我的问题是我的正则表达式似乎不匹配(我总是得到无),即使我使用正则表达式。* 我试图剥离我的"线"因为我打印时似乎有换行符#34; line"在自身。但这并没有解决它
这是我的代码:
import re
p = re.compile(r"""
Foldername.*
,NULL
""", re.VERBOSE)
i = 0
output = open('pdu.temp', 'r')
for line in output:
newline = line.strip() # stripped the line here
print newline
m = p.match(newline)
print m
if m:
print "Until now I found " + str(i) + "matches" + '\n'
# print i + ":" + line
i += 1
output.close()
运行脚本后的输出:
Foldername;Contact Name;location: Location;IP Address
None
Foldername;PDU-A8094;location: ;172.27.0.44
None
Foldername;PDU-A8011;location: ;172.27.0.56
None
Foldername;PDU-8000;location: ;172.27.0.69
None
Foldername;PDU-A8009;location: ;172.27.0.64
None
Foldername;PDU-A8091;location: ;172.27.0.48
帮助我了解如何调试这将是很棒的!
答案 0 :(得分:0)
我不知道你想要什么,尝试发布示例输出。
但也许这会匹配你想要的?
import re
p = re.compile(r'Foldername;(.*);location: (.*);(.*)')
i = 0
with open('input.txt', 'r') as input:
for line in input:
m = p.match(line)
if m:
print "Until now I found " + str(i) + " matches" + '\n'
# print i + ":" + line
i += 1
如果你想要的话,可以考虑改变
if m:
print "Until now I found " + str(i) + " matches" + '\n'
i += 1
到
if m:
i += 1
print "Until now I found " + str(i) + " matches" + '\n'
在输出时避免0。 我的input.txt文件包含:
Foldername;Contact Name;location: Location;IP Address
None
Foldername;PDU-A8094;location: ;172.27.0.44
None
Foldername;PDU-A8011;location: ;172.27.0.56
None
Foldername;PDU-8000;location: ;172.27.0.69
None
Foldername;PDU-A8009;location: ;172.27.0.64
None
Foldername;PDU-A8091;location: ;172.27.0.48
答案 1 :(得分:0)
相反,你应该尝试:
from __future__ import print_statement
import re
p = re.compile(r"""
^
Foldername;PDU
""", re.VERBOSE)
output = open('pdu.temp', 'r')
i = 0;
for line in output:
newline = line.strip() # stripped the line here
m = p.match(newline)
if m:
print("Until now I found " + str(i) + " matches")
i += 1
print('{0}:{1}\n'.format(i, line))
请注意,from __future__ import print_statement
包含在内,因此相同的代码适用于Python 2.7和Python 3.x。