【问题标题】:How to separate the prefix in words that are 'di'?如何分隔'di'单词中的前缀?
【发布时间】:2019-07-31 04:33:16
【问题描述】:

我想把“di”这个词后面跟字母后整合到单词中的一些前缀分开。

sentence1 = "dipermudah diperlancar"
sentence2 = "di permudah di perlancar"

我希望输出是这样的:

output1 = "di permudah di perlancar"
output2 = "di permudah di perlancar"

Demo

【问题讨论】:

    标签: python regex python-3.x string string-matching


    【解决方案1】:

    这个表达式可能在某种程度上起作用:

    (di)(\S+)
    

    如果我们的数据看起来像问题中的一样简单。否则,我们会在表达式中添加更多边界。

    测试

    import re    
    regex = r"(di)(\S+)"    
    test_str = "dipermudah diperlancar"    
    subst = "\\1 \\2"    
    
    print(re.sub(regex, subst, test_str))
    

    表达式在regex101.com 的右上方面板中进行了解释,如果您想探索/简化/修改它,在this link 中,您可以查看它如何与一些示例输入进行匹配,如果您愿意的话。

    【讨论】:

      【解决方案2】:

      这是使用re.sub 的一种方法:

      sentence1 = "adi dipermudah diperlancar"
      output = re.sub(r'(?<=\bdi)(?=\w)', ' ', sentence1)
      print(output)
      

      输出:

      adi di permudah di perlancar
      

      这里的想法是在紧接其前的是前缀di 时插入一个空格,然后是其他单词字符。

      【讨论】:

        猜你喜欢
        • 2019-01-23
        • 1970-01-01
        • 2012-01-07
        • 2012-07-25
        • 2023-03-20
        • 2014-01-04
        • 2019-12-19
        • 2020-01-06
        • 2021-02-09
        相关资源
        最近更新 更多