Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正则表达式的名称错误_Python_Regex - Fatal编程技术网

Python 正则表达式的名称错误

Python 正则表达式的名称错误,python,regex,Python,Regex,我试图用正则表达式解析文件内容,如下代码所示。如果我在“If”套件中打印系统名称,它就会工作。但如果我尝试在外面的任何地方做,那就是抛出名称错误。任何帮助都将不胜感激 #!/usr/bin/python import re f=open("cdp-nei1.txt") f=f.readlines() for data in f: cdp_line = data.split("\n") for line in cdp_line: if "System Name"

我试图用正则表达式解析文件内容,如下代码所示。如果我在“If”套件中打印系统名称,它就会工作。但如果我尝试在外面的任何地方做,那就是抛出名称错误。任何帮助都将不胜感激

#!/usr/bin/python
import re
f=open("cdp-nei1.txt")
f=f.readlines()

for data in f:
    cdp_line = data.split("\n")
    for line in cdp_line:
        if "System Name" in line:
            systemname = re.search(r"System Name:(.+)",line)
            systemname =  systemname.group(1)
            print systemname
/show-cdp.py

路由器1


如果第一行不包含系统名,则不会定义systemname变量,因为您没有进入If块。但在if块之后,您仍在尝试打印它。。。而且它还没有定义,因此您会出错。

请再次参阅“谢谢”。但在那个里,他们说If语句并没有它的范围。所以这应该行得通。否?您是说系统名可能会在文件中出现多次?您使用的是哪个python版本?系统名会出现多次。马克斯·诺尔的回答帮助我理解了我犯的错误。谢谢。就这样。我创建了一个空列表,并将系统名附加到for循环中。现在可以了。谢谢你的帮助。
#!/usr/bin/python
import re
f=open("cdp-nei1.txt")
f=f.readlines()

for data in f:
    cdp_line = data.split("\n")
    for line in cdp_line:
        if "System Name" in line:
            systemname = re.search(r"System Name:(.+)",line)
            systemname =  systemname.group(1)
        print systemname

***

 ./show-cdp.py 

Traceback (most recent call last):
  File "./show-cdp.py", line 12, in <module>
    print systemname
NameError: name 'systemname' is not defined
Device ID:Router1
System Name: Router1

Interface address(es):
    IPv4 Address: 10.0.0.1
Platform: N5K-C5672UP, Capabilities: Router Switch IGMP Filtering Supports-STP-Dispute
Interface: mgmt0, Port ID (outgoing port): Ethernet101/1/47
Holdtime: 179 sec

Version:
Cisco Nexus Operating System (NX-OS) Software, Version 7.0(1)N1(1)

Advertisement Version: 2

Native VLAN: 1
Duplex: full

MTU: 1500
Physical Location: Somewhere,United States
Mgmt address(es):
    IPv4 Address: 10.0.0.1