python - 解析 [value](type) 格式的句子

标签 python regex

我想从给定的句子中解析和提取键值,它们遵循以下格式:
我想在 [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/

相关文章:

javascript - 需要帮助编写用户名正则表达式

用于简单模式的 Java 正则表达式

python - 使用 anaconda 升级后,jupyter 不导入 numpy

python - 在 twilio Rest API 上使用 Status_Callback

python - 使用 tweepy 保存推文的全文

c# - 带有第一个大写字符+数字的正则表达式

Javascript:类似于带有属性名称的 string.format

python - 自定义 Django 数据库前端

python - AngularJS request.POST 返回 QueryDict : {}

javascript - 我是错觉了,还是 JS RegExp 支持可选的重复范围?