我正在嘗試將字符串拆分為特定的關(guān)鍵字。我有一個(gè)關(guān)鍵詞/字符列表。例如:我有一個(gè)關(guān)鍵字列表{'1', '2', '3', '4', '5', 'let', 'while'}我有一個(gè)字符串let2while4我想輸出一個(gè)包含{'let', '2', while', '4'}這可能嗎?我目前只使用帶有 ' ' 的分隔符將其拆分謝謝!編輯:使用下面的 Gilch 的答案適用于下面的示例,但是當(dāng)我輸入完整的關(guān)鍵字時(shí),我收到了這些錯(cuò)誤: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我的完整關(guān)鍵字包括:關(guān)鍵字 = {'1','2','3','4','5','6','7','8','9','0','x','y' ,'z','+','-','*','>','(',')',';','$','let','while','else',' ='}
1 回答

萬(wàn)千封印
TA貢獻(xiàn)1891條經(jīng)驗(yàn) 獲得超3個(gè)贊
用于'|'.join()從您的關(guān)鍵字制作正則表達(dá)式模式。
>>> 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'}
如果您的關(guān)鍵字可能包含正則表達(dá)式控制字符,您可以re.escape()在加入之前使用它們。
>>> re.findall('|'.join(map(re.escape, keywords)), string)
添加回答
舉報(bào)
0/150
提交
取消