2015-12-30 40 views
2

我有一個文本文件,其中包括這樣的臺詞:re.findall()不匹配與它的發現

<pattern number=1 theme=pseudo> 
<pattern number=2 theme=foo> 
<pattern number=3 theme=bar> 

我選擇這個功能的隨機行:

def find_random_pattern(theme): 
    found_lines = [] 
    pattern = open('poempatterns.txt','r') 
    for line in pattern: 
     found = re.findall("theme="+theme,line) 
     for match in found: 
      found_lines.append(line) 

    selectedline = random.choice(found_lines) 
    return selectedline 

假設它返回<pattern number=1 theme=pseudo>

當我與此條件檢查,它返回False

if find_random_pattern("pseudo") == "<pattern number=1 theme=pseudo>": 
    return True 
else: 
    return False 

爲什麼這兩個字符串不匹配?

+3

如果你只在'line'中檢查'theme = pseudo',那麼我真的不明白你爲什麼需要'regex',只需'in'就夠了 –

+1

**提示:**如果您執行print(find_random_pattern(「pseudo」)),會發生什麼情況? (或'print(re.findall(...))'。) –

回答

4

你期待的是re.findall返回整條生產線,但返回匹配的部分:

>>> line = "<pattern number=1 theme=pseudo>" 
>>> import re 
>>> re.findall("theme=pseudo", line) 
['theme=pseudo'] 

我建議你使用的是整條生產線相匹配的模式,例如:

>>> re.findall(".*theme=pseudo.*", line) 
['<pattern number=1 theme=pseudo>'] 

你最終的代碼將如下所示:

def find_random_pattern(theme): 
    found_lines = [] 
    pattern = open('poempatterns.txt','r') 
    for line in pattern: 
     # Call strip() just in case you have some blank spaces or \n at the end 
     found = re.findall(".*theme=%s.*" % theme, line.strip()) 
     for match in found: 
      found_lines.append(line) 

    selectedline = random.choice(found_lines) 
    return selectedline 

解決方案有點多ncise是:

import random 
import re 
import string 

def find_random_pattern(theme): 
    lines = open('poempatterns.txt','r').readlines() 
    stripped_lines = map(string.strip, lines) 
    found_lines = filter(lambda l: re.match(".*theme=%s.*" % theme, l), stripped_lines) 
    return random.choice(found_lines) 
+0

你的第一個函數也返回false,但第二個函數工作。謝謝 – JayGatsby

2

re.findall不會返回比賽只不是整個line。 從Python Docs.引用:

re.findall(圖案,字符串標誌= 0)返回圖案的所有非重疊 匹配字符串,作爲字符串的列表。該字符串是從左到右掃描的 ,匹配按找到的順序返回。如果 模式中存在一個或多個組,則返回 組的列表;如果該模式具有多個 組,則這將是元組列表。除非他們觸及另一場比賽的開始 ,否則結果中會包含空符。

DEMO:

>>> s = 'Good morning Gotham!' 
>>> re.findall('Go', s) 
['Go', 'Go'] 

這就是說,如果你的要求是找到,如果theme退出在line,那麼你真的不需要爲regex

def find_random_pattern(theme): 
    with open('poempatterns.txt','r') as pattern: 
     found_lines = [line for line in pattern if theme in line] 
    selectedline = random.choice(found_lines) 
    return selectedline