2009-11-30 7 views
17

str.splitと同等のものがPythonでも区切り文字を返しますか?Pythonでデリミタを保持する文字列をトークン化

トークンの一部を処理した後、出力用の空白のレイアウトを保持する必要があります。

例:

>>> s="\tthis is an example" 
>>> print s.split() 
['this', 'is', 'an', 'example'] 

>>> print what_I_want(s) 
['\t', 'this', ' ', 'is', ' ', 'an', ' ', 'example'] 

ありがとう!

+1

1 - 興味深い質問、 'splitlines'は' keepends'パラメータが、split' 'のためのそのようなものを持っているようです。奇妙に思えます(http://docs.python.org/library/stdtypes.html#str.splitlines)。 –

答えて

19

どの程度

import re 
splitter = re.compile(r'(\s+|\S+)') 
splitter.findall(s) 
+0

( '(\ s + | \ w + | \ S +)'と考えると)エレガントで簡単に拡張できます。 – hop

6
>>> re.compile(r'(\s+)').split("\tthis is an example") 
['', '\t', 'this', ' ', 'is', ' ', 'an', ' ', 'example'] 
4

reモジュールは、この機能を提供します。

(Pythonドキュメントから引用)
>>> import re 
>>> re.split('(\W+)', 'Words, words, words.') 
['Words', ', ', 'words', ', ', 'words', '.', ''] 

例(空白で分割)の場合は、re.split('(\s+)', '\tThis is an example')を使用してください。

キーは、分割する正規表現をキャプチャカッコで囲むことです。こうすることで、デリミタが結果リストに追加されます。

編集:指摘したように、任意の前後の区切り記号ももちろんリストに追加されます。これを避けるには、まず入力文字列に.strip()メソッドを使用します。

+0

OPの文字列を使用しないと、空の文字列が返されるリストの最初の要素として含まれているという事実がマスクされます。 – hop

+0

ありがとうございます。私はそれに応じて私の投稿を編集しました(この場合、OPのスペック(「空白を残したい」)と彼の例は矛盾していました)。 –

+0

いいえ、それは...現在の動作の1つの例と、望ましい動作の1つの例がありました。 – fortran

-1

みんなありがとうreモジュールのためのポインティングのために、私はまだその間で決定しようとしていると私はベンチマークそれらをいただきたい時間を持っていた場合のシーケンスを返す私自身の機能...

def split_keep_delimiters(s, delims="\t\n\r "): 
    delim_group = s[0] in delims 
    start = 0 
    for index, char in enumerate(s): 
     if delim_group != (char in delims): 
      delim_group ^= True 
      yield s[start:index] 
      start = index 
    yield s[start:index+1] 

を使用していますxD

+0

python 2.5以降を使用している場合、正規表現や独自のホイールを作成する必要はありません。私の答えを見てください。 – ghostdog74

3

pyparsingを見ましたか? the pyparsing wikiから借り例:

>>> from pyparsing import Word, alphas 
>>> greet = Word(alphas) + "," + Word(alphas) + "!" 
>>> hello1 = 'Hello, World!' 
>>> hello2 = 'Greetings, Earthlings!' 
>>> for hello in hello1, hello2: 
...  print (u'%s \u2192 %r' % (hello, greet.parseString(hello))).encode('utf-8') 
... 
Hello, World! → (['Hello', ',', 'World', '!'], {}) 
Greetings, Earthlings! → (['Greetings', ',', 'Earthlings', '!'], {}) 
関連する問題