如何将字符串拆分为特定的关键字?

时间:2019-10-15 03:12:16

标签: python string split

我正在尝试将字符串拆分为特定的关键字。我有一个关键字/字符列表。

例如: 我有一个关键字列表{'1', '2', '3', '4', '5', 'let', 'while'}

我有一个字符串let2while4

我要输出一个包含{'let', '2', while', '4'}

的列表

这可能吗?我目前仅使用带有分隔符的分隔符 ''

谢谢!

编辑: 在下面的示例中,使用下面的Gilch答案是可行的,但是当我输入完整的关键字时,出现以下错误:

Traceback (most recent call last):
File "parser.py", line 14, in <module>
list = re.findall(f"({'|'.join(keywords)})", input)
File "/usr/lib/python3.7/re.py", line 223, in findall
File "/usr/lib/python3.7/sre_parse.py", line 816, in _parse
p = _parse_sub(source, state, sub_verbose, nested + 1)
File "/usr/lib/python3.7/sre_parse.py", line 426, in _parse_sub
not nested and not items))
File "/usr/lib/python3.7/sre_parse.py", line 651, in _parse
source.tell() - here + len(this))
re.error: nothing to repeat at position 17

我的完整关键字包括:

关键字= {'1','2','3','4','5','6','7','8','9','0','x', 'y','z','+','-','*','>','(',')',';','$','let','while','else ','='}

1 个答案:

答案 0 :(得分:5)

使用'|'.join()从您的关键字中创建一个正则表达式模式。

>>> keywords = {'1', '2', '3', '4', '5', 'let', 'while'}
>>> string = 'let2while4'
>>> import re
>>> re.findall('|'.join(keywords), string)
['let', '2', 'while', '4']
>>> set(_)
{'let', '2', 'while', '4'}

如果您的关键字可能包含正则表达式控制字符,则可以在加入之前对它们使用re.escape()

>>> re.findall('|'.join(map(re.escape, keywords)), string)
相关问题