0

I have strings like this:

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

I hope the output string like:

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

not

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

I tried to use str.find() but it's not suitable.

if strA.find(strB) != -1:    
    x = strA.find(strB)
    listA = list(strA)
    listA.insert(x, strB)
    output = ''.join(listA)
Furry Bear
  • 27
  • 4
  • 6
    What are the merging rules? – Klaus D. Jul 12 '19 at 08:20
  • This may help [Insert some string into given string at given index in Python](https://stackoverflow.com/questions/4022827/insert-some-string-into-given-string-at-given-index-in-python) – Tek Nath Acharya Jul 12 '19 at 08:24
  • @KlausD. I update my question, thanks! It want merging the most similar sentence. – Furry Bear Jul 12 '19 at 08:30
  • 1
    @FurryBear, ok, what's the expected output for `"Today is hot. My dog love hot dog, milk. But my cat loves hot dog and fish"` ? – RomanPerekhrest Jul 12 '19 at 08:33
  • 1
    this problem is very similar to [sequence alignment](https://en.wikipedia.org/wiki/Sequence_alignment) in bioinformatics. an aim there is to find the closest matching substring while allowing for mistakes. you could then use this match to do your insertion/replacement of text – Sam Mason Jul 12 '19 at 12:15
  • @SamMason it's very useful, thank you very much! – Furry Bear Jul 15 '19 at 01:08

2 Answers2

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

strA = strA.replace('dog,',strB);
print(strA);

this is not a dynamic solution. but can work for this problem

Abhishek-Saini
  • 733
  • 7
  • 11
0

You can do a reverse lookup and return the best matched result.

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))

Result:

Today is hot. My dog love hot dog and bread and cheese, milk, and candy.
Henry Yik
  • 22,275
  • 4
  • 18
  • 40