[英]Python: Splitting a string into words, saving separators
我有一个字符串:
'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)
我可能首先将空格上的.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
的末尾或开头有一个''
。 但是,这很容易检查和消除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.