2013-03-15 59 views
0

我嘗試編寫一個python腳本來分析數據txt.I想讓腳本做這樣的事情: 找到所有的時間數據在一行中,並比較它們。但這是我第一次寫RE語法。所以我在1日寫了一個小腳本。Python中的正則表達式語法

和我的腳本是:

import sys 
txt = open('1.txt','r') 
a = [] 
for eachLine in txt: 
    a.append(eachLine) 
import re 
pattern = re.compile('\d{2}:\d{2}:\d{2}') 
for i in xrange(len(a)): 
    print pattern.match(a[i]) 
#print a 

和輸出總是

我的TXT就像圖片: enter image description here

什麼問題? PLZ幫助我。多謝。

和我的python是python 2.7.2.my os是windows xp sp3。

回答

0

難道你不會錯過你的正則表達式中的「:」嗎?我覺得你的意思

re.compile('\d{2}:\d{2}:\d{2}') 

其他問題是:

首先,如果你想在孔要搜索的文本,使用search代替match。其次,要訪問您的結果,您需要在搜索返回的匹配對象中調用group()。

試試:

import sys 
txt = open('1.txt','r') 
a = [] 
for eachLine in txt: 
    a.append(eachLine) 
import re 
pattern = re.compile('\d{2}:\d{2}:\d{2}') 
for i in xrange(len(a)): 
    match = pattern.search(a[i]) 
    print match.group() 
#print a 
+0

仍然不起作用。我輸入腳本.... – 2013-03-15 03:26:58

+0

我編輯了原始答案以解決其他問題。 – 2013-03-15 03:48:11

0

我認爲你缺少你的正則表達式的冒號和點。也可以嘗試在整個文本上使用re.search或re.findall。像這樣:

import re, sys 

text = open("./1.txt", "r").read() # or readlines() to make a list of lines 
pattern = re.compile('\d{2}:\d{2}:\d{2}') 

matches = pattern.findall(text) 

for i in matches: 
    print(i);