【问题标题】:How can quickly merge strings in PythonPython中如何快速合并字符串
【发布时间】:2019-07-15 09:48:31
【问题描述】:

我有这样的字符串:

strA = "Today is hot. My dog love hot dog, milk, and candy."
strB = "hot dog and bread"

我希望输出字符串像:

"Today is hot. My dog love hot dog and bread, milk, and candy."

不是

"Today is hot dog and bread. My dog love hot dog, milk, and candy."

我尝试使用str.find() 但不合适。

if strA.find(strB) != -1:    
    x = strA.find(strB)
    listA = list(strA)
    listA.insert(x, strB)
    output = ''.join(listA)

【问题讨论】:

  • 合并规则是什么?
  • @KlausD。我更新我的问题,谢谢!它想要合并最相似的句子。
  • @FurryBear,好的,"Today is hot. My dog love hot dog, milk. But my cat loves hot dog and fish" 的预期输出是什么?
  • 这个问题和生物信息学中的sequence alignment非常相似。目标是在允许错误的同时找到最接近的匹配子字符串。然后你可以使用这个匹配来插入/替换文本

标签: python


【解决方案1】:

您可以进行反向查找并返回最佳匹配结果。

strA = "Today is hot. My dog love hot dog, milk, and candy."
strB = "hot dog and bread"

def replace_method(string_a,string_b):
    s = string_b.split()
    for i in reversed(range(len(s)+1)):
        if " ".join(s[:i]) in string_a:
            return string_a.replace(" ".join(s[:i]),string_b)

print (replace_method(strA,strB))

结果:

Today is hot. My dog love hot dog and bread and cheese, milk, and candy.

【讨论】:

    【解决方案2】:
    strA = "My dog love hot dog, milk, and candy."
    strB = "dog and bread"
    
    strA = strA.replace('dog,',strB);
    print(strA);
    

    这不是动态解决方案。但可以解决这个问题

    【讨论】:

    • 对不起,我的错,我没注意到那个逗号。
    • strB = "hot dog and bread"strA.replace("hot dog", strB) 怎么样?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-27
    • 2020-02-28
    • 2010-11-20
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    相关资源
    最近更新 更多