2017-08-26 21 views
0

我需要編寫一個函數,它需要一個count和一個字符串,並返回字符串中所有長度爲或長於字長字符的單詞列表。int在Python中的正則表達式中不起作用def

我的功能是:

import re 

def find_words(count, a_str): 
    count = int(count) 
    return re.findall(r'\w{},'.format(int(count)), a_str) 

但它不工作,這是返回空列表:

例子:

find_words(4, "dog, cat, baby, balloon, me") 

應返回:

['baby', 'balloon'] 

回答

3

正則表達式不正確。 {}被解釋爲format的佔位符,但您希望它是指定重複次數的正則表達式'{}。您需要在這裏使用r'\w{{{}}}'。注意區別:

>>> r'\w{},'.format(4) 
'\\w4,' 

>>> r'\w{{{},}}'.format(4) 
'\\w{4,}' 

然後它正常工作:

import re 
def find_words(count, a_str): 
    count = int(count) 
    return re.findall(r'\w{{{},}}'.format(count), a_str) 

>>> find_words(4, "dog, cat, baby, balloon, me") 
['baby', 'balloon'] 
+0

謝謝,但爲什麼需要{ {{}}}而不僅僅是{{}}? –

+0

@Dmitriy_kzn文檔說:「如果您需要在文字中包含大括號字符,則可以通過加倍:'{{'和'}}'來逃脫。 [「格式字符串語法」](https://docs.python.org/3/library/string.html#format-string-syntax)並且你想在正則表達式的文本文本中保留一個大括號字符,但你也想要插入'count'。所以'{{'所以它保留'{'和'''格式化。 – MSeifert

2

爲什麼正則表達式?

>>> string = "dog, cat, baby, balloon, me" 
>>> [word for word in string.split(', ') if len(word) >= 4] 
['baby', 'balloon'] 

所以功能可能類似如下:

>>> def find_words(count, a_str): 
...  return [word for word in a_str.split(', ') if len(word) >= count] 
... 
>>> find_words(4, 'dog, cat, baby, balloon, me') 
['baby', 'balloon'] 
+0

如果輸入一個愚蠢但有效的計數,比如0或-1,這比正則表達式更好 –

0

你可以試試這個:

def find_words(count, a_str): 
    s = [re.findall("\w{"+str(count)+",}", i) for i in ["dog, cat, baby, balloon, me"]] 
    return s[0] 

print(find_words(4, ["dog, cat, baby, balloon, me"])) 

輸出:

['baby', 'balloon']