Pythonで区切り文字を保持する文字列をトークン化する
質問
区切り文字も返すPythonの str.split
に相当するものはありますか?
トークンの一部を処理した後、出力の空白レイアウトを保持する必要があります。
例:
>>> s="\tthis is an example"
>>> print s.split()
['this', 'is', 'an', 'example']
>>> print what_I_want(s)
['\t', 'this', ' ', 'is', ' ', 'an', ' ', 'example']
ありがとう!
解決
方法について
import re
splitter = re.compile(r'(\s+|\S+)')
splitter.findall(s)
他のヒント
>>> re.compile(r'(\s+)').split("\tthis is an example")
['', '\t', 'this', ' ', 'is', ' ', 'an', ' ', 'example']
re
モジュールはこの機能を提供します:
>>> import re
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
(Pythonドキュメントから引用)。
例(空白で分割)には、 re.split( '(\ s +)'、 '\ tこれは例です')
を使用します。
キーは、括弧をキャプチャする際に分割する正規表現を囲むことです。これにより、区切り文字が結果のリストに追加されます。
編集:指摘したように、当然のことながら、前後の区切り文字もリストに追加されます。これを回避するには、最初に入力文字列で .strip()
メソッドを使用します。
pyparsingを見たことがありますか? 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', '!'], {})
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のベンチマークを行います
所属していません StackOverflow