[英]How to split string into specific keywords?
我正在嘗試將字符串拆分為特定的關鍵字。 我有一個關鍵詞/字符列表。
例如:我有一個關鍵字列表{'1', '2', '3', '4', '5', 'let', 'while'}
我有一個字符串let2while4
我想 output 一個包含{'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',' ='}
使用'|'.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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.