2016-07-22 44 views
0

我試圖通過谷歌的Python的課程提供給一個列表,一些正則表達式的例子和一個新行打印每個輸出的每個輸出。谷歌的Python的課程:通過正則表達式的列表迭代並打印一個新行

import re 
str='an example word:cat!!' 
match=re.search(r'word:\w\w\w',str) 
if match: 
    print('I found a cat :)',match.group()) ## 'found word:cat' 
else: 
    print('did not find') 


matches=[re.search(r'pi+', 'piiig'),re.search(r'i+', 'piigiiii'),re.search(r'\d\s*\d\s*\d', 'xx1 2 3xx'),re.search(r'\d\s*\d\s*\d', 'xx12 3xx'),re.search(r'\d\s*\d\s*\d', 'xx123xx'),re.search(r'^b\w+', 'foobar'),re.search(r'b\w+', 'foobar')] 
for the_match in matches: 
    matches.append(the_match) 
print("\n".join(matches)) 
#del matches 

當我運行python regex.py,我得到如下:

python regex.py 
I found a cat :) word:cat 

它只是攤位,不產生進一步的輸出。我將不得不按ctrl+c兩次退出。

請讓我如何獲得的輸出,諸如:

re.search(r'pi+', 'piiig') returned (<_sre.SRE_Match object; span=(0, 4), match='piii'>, <_sre.SRE_Match object; span=(1, 3), match='ii'>) 
re.search(r'i+', 'piigiiii') returned <_sre.SRE_Match object; span=(1, 3), match='ii'> 
etc... 

我在Windows 10版本10.0.10586 64位運行的Python 3.5.2。

謝謝!

你的答案(@Buzz)後,我的腳本如下:

import re 
str='an example word:cat!!' 
match=re.search(r'word:\w\w\w',str) 
matches=[re.search(r'pi+', 'piiig'),re.search(r'i+', 'piigiiii'),re.search(r'\d\s*\d\s*\d', 'xx1 2 3xx'),re.search(r'\d\s*\d\s*\d', 'xx12 3xx'),re.search(r'\d\s*\d\s*\d', 'xx123xx'),re.search(r'^b\w+', 'foobar'),re.search(r'b\w+', 'foobar')] 

if match: 
    print('I found a cat :)',match.group()) ## 'found word:cat' 
else: 
    print('No match found.') 

for the_match in matches: 
    print(the_match) 

輸出如下:

I found a cat :) word:cat 
<_sre.SRE_Match object; span=(0, 4), match='piii'> 
<_sre.SRE_Match object; span=(1, 3), match='ii'> 
<_sre.SRE_Match object; span=(2, 9), match='1 2 3'> 
<_sre.SRE_Match object; span=(2, 7), match='12 3'> 
<_sre.SRE_Match object; span=(2, 5), match='123'> 
None 
<_sre.SRE_Match object; span=(3, 6), match='bar'> 

這完美的作品。非常感謝。

回答

2

它一直運行下去的原因是becasue要附加到matches裏面的for循環。你總是加入它,使得列表更長,這反過來使得for循環運行,直到它可以達到結束,但它永遠不會達到它。

for the_match in matches: 
    print (the_match) 
+1

我刪除了'matches.append(the_match'並將print'行更改爲'print(the_match)'並且它工作。我將用新腳本更新我的問題謝謝@ Buzz –

0

你有一個無限循環:

for the_match in matches: 
    matches.append(the_match) 

這將新的項目添加到列表中,直到永遠。我不知道你試圖用這個做什麼,但看起來你可以簡單地刪除這兩行。

+0

謝謝。我刪除了這兩行,並且找到了一條貓:)字:cat 回溯(最近的通話最後): 文件「regex.py」,第13行,在 print(「\ n」.join(matches )) 類型錯誤:序列項0:預計STR例如,_sre.SRE_Match found'然後,我改變了'print'線'打印( 「\ n」。加入(STR(比賽))'和'了,我發現一個貓:) :)文字:貓 回溯(最近通話最後一次): 文件「regex.py」,第13行,在 print(「\ n」.join(str(matches))) TypeError:'str'對象不可調用。「 –