カウントと文字列をとり、文字列中の単語の文字数が長いか長いリストを返す関数を書く必要があります。intがPythonの正規表現内でdefで動作しない
My機能は次のとおりです。
例:
find_words(4, "dog, cat, baby, balloon, me")
が返す:
['baby', 'balloon']
カウントと文字列をとり、文字列中の単語の文字数が長いか長いリストを返す関数を書く必要があります。intがPythonの正規表現内でdefで動作しない
My機能は次のとおりです。
例:
find_words(4, "dog, cat, baby, balloon, me")
が返す:
['baby', 'balloon']
import re
def find_words(count, a_str):
count = int(count)
return re.findall(r'\w{},'.format(int(count)), a_str)
しかし、それは動作しません、それは空のリストを返すです
正規表現が正しくありません。 {}
は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']
なぜ正規表現?
>>> 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または-1のような愚かでも有効なカウントを入力すると、正規表現よりも優れています –
:
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']
おかげで、なぜそれが必要とされます{ {{}}の代わりに{{}}}を使用しますか? –
@Dmitriy_kznドキュメントでは、「リテラルテキストに中括弧文字を含める必要がある場合は、「{{'と'}} 'を倍にすることでエスケープすることができます。 ["Format String Syntax"](https://docs.python.org/3/library/string.html#format-string-syntax)正規表現のリテラルテキストに1つのブレース文字を残したいが、 'count'を挿入します。 '{{'したがって、 '{'と '{'は書式設定に使用します。 – MSeifert