我正在嘗試將字符串拆分為特定的關鍵字。我有一個關鍵詞/字符列表。例如:我有一個關鍵字列表{'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 findallFile "/usr/lib/python3.7/sre_parse.py", line 816, in _parsep = _parse_sub(source, state, sub_verbose, nested + 1)File "/usr/lib/python3.7/sre_parse.py", line 426, in _parse_subnot nested and not items))File "/usr/lib/python3.7/sre_parse.py", line 651, in _parsesource.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 回答

萬千封印
TA貢獻1891條經驗 獲得超3個贊
用于'|'.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)
添加回答
舉報
0/150
提交
取消