我想从给定的句子中解析和提取键值,它们遵循以下格式:
我想在 [1 周](duration) 内让 [samsung](brand) 开心。
我想把它转换成如下的拆分列表:
['我希望', 'samsung:brand', '在', '1 week:duration', '内得到快乐。']
我尝试使用 [
或 )
拆分它:
re.split('\[|\]|\(|\)',s)
给出输出:
['I want to get ',
'samsung',
'',
'brand',
' within ',
'1 week',
'',
'duration',
' to be happy.']
和
re.split('\[||\]|\(|\)',s)
给出以下输出:
['I want to get ',
'samsung](brand) within ',
'1 week](duration) to be happy.']
感谢任何帮助。
注意:这也类似于 stackoverflow 内联链接,如果我们键入:go to [this link](http://google.com)
,它会将其解析为链接。
最佳答案
第一步我们拆分字符串,第二步我们修改字符串:
s = 'I want to get [samsung](brand) within [1 week](duration) to be happy.'
import re
s = re.split('(\[[^]]*\]\([^)]*\))', s)
s = [re.sub('\[([^]]*)\]\(([^)]*)\)', r'\1:\2', i) for i in s]
print(s)
打印:
['I want to get ', 'samsung:brand', ' within ', '1 week:duration', ' to be happy.']
关于python - 解析 [value](type) 格式的句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57524654/