首页 > 解决方案 > 在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)

这是有效的,但效率很低,因为我有数百个这样的词要检查。它也没有涵盖边缘情况,例如如果它是第一个单词就不要添加分隔符,如果它已经存在就不要添加分隔符。任何帮助,将不胜感激。

标签: pythonregex

解决方案


您可能正在寻找的正则表达式是([^,\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)

Python演示!


推荐阅读