11

入力文字列は次のとおりです。

line = "Cat Jumped the Bridge"

出力は「Jumped the Bridge」である必要があります。

私は試した

s2 = re.match('\W+.*', line).group()

しかし、それは戻ります

Traceback (most recent call last):
  File "regex.py", line 7, in <module>
    s2 = re.match('\W+.*', line).group()
AttributeError: 'NoneType' object has no attribute 'group'

だから明らかに試合は失敗した。

提案をありがとう。ジョー

4

6 に答える 6

17

Python の分割maxsplitには、分割の最大量を指定するためのと呼ばれるオプションの 2 番目のパラメーターがあります。

line = "Cat Jumped the Bridge"
s2 = line.split(' ', 1)[1]

のドキュメントを引用するにはstr.split

区切り文字列として sep を使用して、文字列内の単語のリストを返します。maxsplit が指定されている場合、最大で maxsplit 回の分割が行われます

このコードを説明する str.split(' ', 1)と、2 つの要素を持つリストが作成されます。最初の要素は最初の単語 (スペースに到達するまで) であり、2 番目の要素は文字列の残りの部分です。文字列の残りのみを抽出するには、 を使用[1]して 2 番目の要素を示します。

注: 複数のスペースが必要な場合は、次のようNoneに の最初のパラメーターとして使用しstr.splitます。

line = "Cat Jumped the Bridge"
s2 = line.split(None, 1)[1]
于 2012-12-31T06:57:17.663 に答える
5

正規表現に縛られていない場合は、次のようにすることができます。

In [1]: line = "Cat Jumped the Bridge"

In [2]: s2 = ' '.join(line.split()[1:])

In [3]: s2
Out[3]: 'Jumped the Bridge'

line.split()文字列を取得して空白で分割し、各単語をアイテムとして含むリストを返します。

In [4]: line.split()
Out[4]: ['Cat', 'Jumped', 'the', 'Bridge']

そのリストから、次を使用して 2 番目の要素 (最初の単語をスキップ) とそれ以降のすべてを取得します[1:]

In [5]: line.split()[1:]
Out[5]: ['Jumped', 'the', 'Bridge']

そして最後の部分は、 を使用してすべてを結合していjoinます。ここでは、スペース文字を使用して、リスト内のすべての文字列を単一の文字列に「結合」します。

In [6]: ' '.join(line.split()[1:])
Out[6]: 'Jumped the Bridge'
于 2012-12-31T06:16:33.953 に答える
5

次のものも使用できます.partition()

>>> line = "Cat Jumped the Bridge"
>>> word, space, rest = line.partition(' ')
>>> word
'Cat'
>>> space
' '
>>> rest
'Jumped the Bridge'

あなたが今持っているものを修正するには、キャプチャグループを追加して\w代わりに使用\Wします(それらは反対です):

>>> re.match(r'(\w+)', line).group()
'Cat'
于 2012-12-31T06:17:09.283 に答える
3

もっと簡単にできます:

line = "Cat Jumped the Bridge"
s2 = " ".join(line.split()[1:])

正規表現の使用:

line = "Cat Jumped the Bridge"
s2 = re.sub('^\S+\s+', '', line)
于 2012-12-31T06:13:32.333 に答える
1

または.........

words = ["Cat", "Cool", "Foo", "Mate"]
sentence = "Cat Jumped the Bridge"

for word in words:
    if word in sentence:
        sentence = sentence.replace(word, "", 1)
        break

さもないと....

sentence = "Cat Jumped the Bridge"

sentence = sentence.split(" ")
sentence.pop(0)
sentence = " ".join(sentence)
于 2015-01-21T06:23:48.203 に答える