Python Tips: 文字列を複数の区切り文字で分割したい

Pythonで、複数の区切り文字を使って文字列を分割する方法をご紹介します。

結論としては、 re.split を使うやり方がよろしいかと思います。

例として、次の文章を単語に分けてみます。

"I Have a Dream" is a public speech delivered by American civil rights activist Martin Luther King, Jr. on August 28, 1963, in which he called for an end to racism in the United States. Delivered to over 250,000 civil rights supporters from the steps of the Lincoln Memorial during the March on Washington, the speech was a defining moment of the American Civil Rights Movement.I Have a Dream - Wikipedia

import re

t1 = '"I Have a Dream" is a public speech delivered by American civil rights activist Martin Luther King, Jr. on August 28, 1963, in which he called for an end to racism in the United States. Delivered to over 250,000 civil rights supporters from the steps of the Lincoln Memorial during the March on Washington, the speech was a defining moment of the American Civil Rights Movement.'

words1 = filter(lambda w: len(w) > 0, re.split(r'\s|"|,|\.', t1))
# => 空白 " , . などを区切り文字として分割された単語のリスト

re.split には、第1引数に区切り文字を正規表現パターンで、第2引数に分割したい文字列を渡します。第1引数に r'\s|"|,|.' というパターンを渡しているので、空白やカンマ、ピリオドで区切られた文字列を返す形になっています。

re.spilt の結果に filter をかけているのは、区切り文字が連続した場合などに生じる空文字列要素を削除するためです。

以上です。

ちなみに、 str 型にも split というメソッドが用意されているのですが、こちらは単一の文字列パターンのみを受け付けるため、複数の区切り文字を使うことはできないようです。

参考