Python:将字符串拆分为单词,保存分隔符

时间:2011-04-04 17:45:24

标签: python

我有一个字符串:

'Specified, if char, else 10 (default).'

我想把它分成两个元组

words=('Specified', 'if', 'char', 'else', '10', 'default')

separators=(',', ' ', ',', ' ', ' (', ').')

有没有人能快速解决这个问题?

PS:此符号'-'是单词分隔符,不是单词

的一部分

6 个答案:

答案 0 :(得分:4)

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)

答案 1 :(得分:1)

你可以使用正则表达式。

>>> a='Specified, if char, else 10 (default).'
>>> from re import split
>>> split(",? ?\(?\)?\.?",a)
['Specified', 'if', 'char', 'else', '10', 'default', '']

但是在这个解决方案中你应该自己编写这种模式。如果要使用该元组,则应将其内容转换为此解决方案中的regex模式。

答案 2 :(得分:1)

正则表达式找到所有分隔符(假设任何不是字母数字的

import re
re.findall('[^\w]', string)

答案 3 :(得分:0)

我可能会先将空格.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)

答案 4 :(得分:0)

在传递中获取分隔符和单词时,可以使用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)

答案 5 :(得分:0)

这是我对它的抨击:

>>> 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。但是,这很容易检查和消除。