如何在python中使用"While()"

Jam*_*s H -5 python regex python-2.x python-2.7

嗨我下面的所有代码都允许我从数据中提取一些特定的信息,我希望有人帮助我通过使用一段时间来更好地写这个,所以我可以为很多行做这个我现在只有两行(数据)我我是初学者所以,如果有人可以提供帮助请解释,这样我就可以学习,而不仅仅是复制和粘贴=)

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import re 

tableau = []

data = "00:02:12.935 mta         Messages       I Doc O:NVS:FAXG3/ R:NVS:SMTP.0/xxxx@x.fr mid:6499"

result1 = {}
i = re.findall(r"^.[^\ ]*", data ) 
j = re.findall(r"\d+$", data ) 
k = re.findall(r"O:[^\ ]*", data ) 
r = re.findall(r"R:[^\ ]*", data )

result1 = {'Heure':i,'MID':j,'Source':k,'Destination':r} 

data = "00:03:12.935 mta         Messages       I Doc O:NVS:FAXG3/ R:NVS:SMTP.0/xxxxx@xxxxx.fr mid:6599"

result2 = {}
i = re.findall(r"^.[^\ ]*", data ) 
j = re.findall(r"\d+$", data ) 
k = re.findall(r"O:[^\ ]*", data ) 
r = re.findall(r"R:[^\ ]*", data )

result2 = {'Heure':i,'MID':j,'Source':k,'Destination':r} 

tableau.append(result1)
tableau.append(result2)

print tableau 
Run Code Online (Sandbox Code Playgroud)

mgi*_*son 6

这实际上是通过for循环更好地完成的:

data1 = "00:02:12.935 mta         Messages       I Doc O:NVS:FAXG3/ R:NVS:SMTP.0/xxxx@x.fr mid:6499"
data2 = "00:03:12.935 mta         Messages       I Doc O:NVS:FAXG3/ R:NVS:SMTP.0/xxxxx@xxxxx.fr mid:6599"
data_list = [ data1, data2 ] #store the data in a list so we can iterate over it
tableau = [] #create a list to hold our output
for data in data_list:  #iterate over the list, getting 1 "data" at a time
    #extract info we want
    i = re.findall(r"^.[^\ ]*", data ) 
    j = re.findall(r"\d+$", data ) 
    k = re.findall(r"O:[^\ ]*", data ) 
    r = re.findall(r"R:[^\ ]*", data )

    #create dictionary and append it to tableau
    tableau.append({'Heure':i,'MID':j,'Source':k,'Destination':r})
Run Code Online (Sandbox Code Playgroud)

更高级的用户可能会在这里使用一个函数,它将字符串作为输入并返回所需数据的字典:

def extract(data):
    i = re.findall(r"^.[^\ ]*", data ) 
    j = re.findall(r"\d+$", data ) 
    k = re.findall(r"O:[^\ ]*", data ) 
    r = re.findall(r"R:[^\ ]*", data )
    return {'Heure':i,'MID':j,'Source':k,'Destination':r}
Run Code Online (Sandbox Code Playgroud)

现在你可以在列表理解中使用它:

tableau = [extract(data) for data in data_list]
Run Code Online (Sandbox Code Playgroud)

从评论中,看起来你正在从文件中获取数据行.那更好(谁想要输入所有这些字符串?).现在我们可以缩短到:

with open('filename') as fin:
    tableau = [extract(data) for data in fin]
Run Code Online (Sandbox Code Playgroud)

使用with介绍另一个python结构 - (上下文管理器).这有点复杂,但它是打开文件的首选方式.对于文件对象,它在功能上等同于:

fin = open('filename')
tableau = ...
fin.close()
Run Code Online (Sandbox Code Playgroud)