2015-05-04 71 views
1

解析我有列表这样得到的字符串在Python列表

["<name:john student male age=23 subject=\computer\sience_{20092973}>", 
"<name:Ahn professor female age=61 subject=\computer\math_{20092931}>"] 

我想用{} 20092973拿到学生,{20092931}。

,所以我想拆列出这样

我期望的结果1是本(输入{20092973})

"student" 

我期待的结果2是这个(输入{20092931})

"professor" 

我已经在搜索...但我找不到..抱歉..

我怎么能THI S'

+0

你从哪里得到这个列表?格式大概是在某个地方定义的;如果可以的话,最好使用它,而不是猜测它。 – abarnert

+0

我在scapy中得到这个列表。我让函数修改scapy。 – Somputer

+0

origin list is [''] – Somputer

回答

5

我不认为你应该在第一时间做这个。不像你的玩具的例子,你的真正的问题不涉及一些笨拙的格式的字符串;它涉及Scapy NetworkInterface对象。哪些属性可以直接访问。你只需要解析它,因为你存储了它的字符串表示。只是不要那样做;存储您实际需要的属性时,您将它们作为属性。

NetworkInterface对象不是文档中描述的(因为它是Windows的特定代码的实现细节),但你可以交互地检查它像Python中的任何其他类别(例如,dir(ni)会显示所有属性),或者只是看看the source。你想要的值是namewin_name。所以,而不是print ni,只是做一些像print '%s,%s' % (ni.name, ni.win_name)。然后,解析一些其他程序中的结果将是微不足道的,而不是脖子上的痛苦。或者,更好的是,如果你真的在Scapy本身使用它,只需直接从{ni.win_name: ni.name for ni in nis}中制作字典即可。 (或者,如果你正在运行Scapy的对Python的2.5或东西,dict((ni.win_name, ni.name) for ni in nis)。)


但是当你问它来回答这个问题(也许你已经捕获的所有数据,并已经太晚了捕捉新数据,所以现在我们被困在你以前的错误中......),这里有三个步骤:(1)找出如何将其中一个字符串解析为其组成部分。 (2)在循环中构建一个将数字映射到名称的字典。 (3)只需使用字典进行查找。

对于解析,我会使用正则表达式。例如:

<name:\S+\s(\S+).*?\{(\d+)\}> 

Regular expression visualization

Debuggex Demo

现在,让我们构建的字典:

r = re.compile(r'<name:\S+\s(\S+).*?\{(\d+)\}>') 
matches = (r.match(thing) for thing in things) 
d = {match.group(2): match.group(1) for match in matches} 

现在:

>>> d['20092973'] 
'student' 
+0

d = {match.group(2):match.group(1)匹配匹配}显示我无效的语法错误..对不起.. – Somputer

+0

@ user3683061:没有无效的语法错误。至少在Python 2.7中,这是你声称你正在使用的。 – abarnert

+0

@ user3683061:另外请注意,我给你的模式是针对你询问的玩具格式,而不是你的真实格式。 – abarnert

2

代码:

def grepRole(role, lines): 
    return [line.split()[1] for line in lines if role in line][0] 

l = ["<name:john student male age=23 subject=\computer\sience_{20092973}>", 
    "<name:Ahn professor female age=61 subject=\compute\math_{20092931}>"] 
print(grepRole("{20092973}", l)) 
print(grepRole("{20092931}", l)) 

输出:

student 
professor 
+0

谢谢!这也运作良好! – Somputer

2
current_list = ["<name:john student male age=23 subject=\computer\sience_{20092973}>", "<name:Ahn professor female age=61 subject=\computer\math_{20092931}>"] 

def get_identity(code): 
    print([row.split(' ')[1] for row in current_list if code in row][0]) 


get_identity("{20092973}") 

正则表达式很好,但对于我来说,菜鸟,正则表达式是另一大问题...

+0

谢谢!这也运作良好! – Somputer