python - 在python中的某个模式之前在字符串中添加分隔符
问题描述
我有一个特定单词的列表
["area", "building", "street no", "floor"]
如果在字符串中以下单词中的任何一个由冒号(:) 后接,我需要在该单词之前添加一个分隔符(最好是逗号)。例如:
sample_input = "area : al mansorah street no : 30 building : xyz tower floor: 3rd"
expected_output = "area: al mansorah, street no: 30, building: xyz tower, floor: 3rd"
这是我目前的实现:
sentence= "area : al mansorah street no : 30 building : 6 floor : 3rd"
words = ["area", "building", "street no", "floor"]
for x in words:
regex = re.escape(x) + r"\s+:"
rep_str = ", " + x + ":"
sentence = re.sub(regex, rep_str, sentence)
这是有效的,但效率很低,因为我有数百个这样的词要检查。它也没有涵盖边缘情况,例如如果它是第一个单词就不要添加分隔符,如果它已经存在就不要添加分隔符。任何帮助,将不胜感激。
解决方案
您可能正在寻找的正则表达式是([^,\s])(\s+(?:your|words|here)\s*:)
因为它非常适合 python 并且可以动态增长。您可以使用 for 循环构建数百个单词的正则表达式,然后运行一次,而不是使用 for 循环来运行这个正则表达式。
([^\s,])
捕获一个非逗号、非空白字符 - 如果已经有一个逗号,或者这是该行中的第一个单词,它将被忽略。(\s+(?:your|words|here)\s*:)
捕获一个或多个空白字符,后跟列表中的任何单词,并以冒号结尾。
#the first part of the string
rex_str = "([^,\s])(\s+(?:"
#the first word
rex_str += words[0]
#get the rest of the words into the non capture group
for i in range(1, len(words)):
rex_str += "|"
rex_str += words[i]
#close the regex
rex_str += ")\s*:)"
#add a comma between the first and second capture groups
sentence = re.sub(rex_str, "\g<1>,\g<2>", sentence)
推荐阅读
- angular - HTTP GET 有效,但其他 HTTP 方法返回 401 - Angular 9 Asp.Net Core 3.1 JWT 授权
- javascript - 将数据添加到 Firebase 实时数据库
- freeradius - FreeRadius 3.0.13 + Google Auth + SSSD + Active Directory - 通过 AD 安全组过滤
- php - 如何将帖子“类别”选项添加到自定义 Wordpress 主题?
- python - 如何在python中对多个变量使用for循环
- visual-studio - 当在远程集群上激活安全二重奏时,如何配置 vs-code SFTP 以保存?
- awesome-wm - 在任务列表中对 Windows 进行分组
- postgresql - Postgres - 如何动态生成用户和密码
- python - 创建单例 - 如何保存实例
- c++ - 如何在 QLabel 中正确实现倒数计时器