2016-03-06 63 views
-7

我正在编写一个程序来获取用户输入的输出。用户输入一个IP地址,然后我需要显示上面一行的特定部分。在文件中搜索IP地址

这里是文件:

MOT物理/ABC-RD0.CLD/CPQSCWSSF001f1-V.80 {
poolcoin /ABC-RD0.CLD/123.45.67.890:88
IP的协议TCP
掩码255.255.255.255
/通用/ SOURCE_ADDR {
默认是
MOT物理/ABC-RD0.CLD/CPQSCWSSF001f1-V.80 {
型材{
/常用/ HTTP {}
/普通/网络服务器的TCP-LAN-优化{
上下文服务器侧
}
MOT物理/ABC-RD0.CLD/BBQSCPQZ001f1-V.80 {
poolcoin /ABC-RD0.CLD /123.45.67.890:88
IP的协议TCP
掩模255.255.255.255

样本与期望的输出输入:

我们er输入IP和输出应为:

用户输入: 123.45.67.890
输出:CPQSCWSSF001f1 < --------------------------- -

用户输入:123.45.67.890
输出:BBQSCPQZ001f1 < ----------------------------

我的代码到目前为止:

#!/usr/bin/env python 

import re 

ip = raw_input("Please enter your IP: ") 

with open("test.txt") as open file: 
    for line in open file: 
     for part in line.split(): 
      if ip in part: 
       print part -1 
+1

stackoverflow为您提供了一个很好的格式化内容的工具,请使用它们。 – fronthem

+0

请先纠正您的标题,说明实际问题。 –

+0

请对输入123.45.67.890进行两次说明,但得到不同的输出。什么是原因? – fronthem

回答

0

以下代码片段为您提供了一个元组字符串/ IP地址:

import re 

string = """ 
mot physical /ABC-RD0.CLD/CPQSCWSSF001f1-V.80 { 
poolcoin /ABC-RD0.CLD/123.45.67.890:88 
ip-protocol tcp 
mask 255.255.255.255 
/Common/source_addr { 
default yes 
mot physical /ABC-RD0.CLD/CPQSCWSSF001f1-V.80 { 
profiles { 
/Common/http { } 
/Common/webserver-tcp-lan-optimized { 
context serverside 
} 
mot physical /ABC-RD0.CLD/BBQSCPQZ001f1-V.80 { 
poolcoin /ABC-RD0.CLD/123.45.67.890:88 
ip-protocol tcp 
mask 255.255.255.255 
""" 

rx = re.compile(""" 
       ^mot   # look for mot at the beginning 
       (?:[^/]+/){2} # two times no/followed by/
       (?P<name>[^-]+) # capture everything that is not - to "name" 
       (?:[^/]+/){2} # the same construct as above 
       (?P<ip>[\d.]+) # capture digits and points 
       """, re.VERBOSE|re.MULTILINE) 

matches = rx.findall(string) 
print matches 
# output: [('CPQSCWSSF001f1', '123.45.67.890'), ('BBQSCPQZ001f1', '123.45.67.890')] 

请参阅a demo on ideone.com
也许你会更好地使用re.finditer(),并在找到你的IP地址后停止执行。