我有一個字符串:的Python:將字符串分割的話,節省分離
'Specified, if char, else 10 (default).'
我想把它分成兩個元
words=('Specified', 'if', 'char', 'else', '10', 'default')
separators=(',', ' ', ',', ' ', ' (', ').')
有沒有人有這樣一個快速的解決方案?
PS:這個符號'-'
是一個字分隔符,而不是字
我有一個字符串:的Python:將字符串分割的話,節省分離
'Specified, if char, else 10 (default).'
我想把它分成兩個元
words=('Specified', 'if', 'char', 'else', '10', 'default')
separators=(',', ' ', ',', ' ', ' (', ').')
有沒有人有這樣一個快速的解決方案?
PS:這個符號'-'
是一個字分隔符,而不是字
import re
line = 'Specified, if char, else 10 (default).'
words = re.split(r'\)?[, .]\(?', line)
# words = ['Specified', '', 'if', 'char', '', 'else', '10', 'default', '']
separators = re.findall(r'\)?[, .]\(?', line)
# separators = [',', ' ', ' ', ',', ' ', ' ', ' (', ').']
如果你真的想要的元組將結果傳遞在tuple()
,如果你不想words
也有空條目(從逗號和空格之間),使用以下命令:
words = [x for x in re.split(r'\)?[, .]\(?', line) if x]
或
words = tuple(x for x in re.split(r'\)?[, .]\(?', line) if x)
的一部分,您可以使用正則表達式這一點。
>>> a='Specified, if char, else 10 (default).'
>>> from re import split
>>> split(",? ?\(?\)?\.?",a)
['Specified', 'if', 'char', 'else', '10', 'default', '']
但是在這個解決方案中,您應該自己編寫該模式。如果你想使用這個元組,你應該把它的內容轉換爲這個解決方案中的正則表達式模式。
正則表達式來找到所有分隔符(假定任何非字母數字
import re
re.findall('[^\w]', string)
我在我的解決方案中使用了正則表達式,謝謝=) – Dan 2011-04-07 10:14:55
我大概會先將空格上的.split()
放入列表中,然後遍歷列表,使用正則表達式檢查字邊界後面的字符。
import re
s = 'Specified, if char, else 10 (default).'
w = s.split()
seperators = []
finalwords = []
for word in words:
match = re.search(r'(\w+)\b(.*)', word)
sep = '' if match is None else match.group(2)
finalwords.append(match.group(1))
seperators.append(sep)
在通獲得兩個分離器和文字,你可以使用的findall如下:
import re
line = 'Specified, if char, else 10 (default).'
words = []
seps = []
for w,s in re.findall("(\w*)([), .(]+)", line):
words.append(w)
seps.append(s)
這裏是我的裂紋吧:
>>> p = re.compile(r'(\)? *[,.]? *\(?)')
>>> tmp = p.split('Specified, char, else 10 (default).')
>>> words = tmp[::2]
>>> separators = tmp[1::2]
>>> print words
['Specified', 'char', 'else', '10', 'default', '']
>>> print separators
[', ', ', ', ' ', ' (', ').']
唯一的問題是,你可以有一個''
在words
的末尾或開頭,如果在句子的開頭/結尾處有一個分隔符,前後沒有任何分隔符。但是,這很容易檢查和消除。
你能給我們一套完整的分隔符?目前,我們知道'['',',','(',')。']'。還有更多嗎?或者,或許應該將每個不是字母數字的字符視爲分隔符?你需要更具體。 – 2011-04-04 18:03:14
除了托馬斯提出的問題之外,是否有一個原因,即括號是用空格分組的,但逗號不是? – 2011-04-04 18:05:05
我已經爲我重寫了正則表達式現在它使用非字母數字字符作爲分隔符'^ [a-Z0-9]' – Dan 2011-04-06 08:51:41