Wie kann man die Unterschiede zwischen zwei Saiten in Python hervorheben?Python

Python-Programme
Anonymous
 Wie kann man die Unterschiede zwischen zwei Saiten in Python hervorheben?

Post by Anonymous »

Ich möchte die Unterschiede zwischen zwei Zeichenfolgen in einer Farbe unter Verwendung von Python-Code hervorheben.

Code: Select all

sentence1 = "I'm enjoying the summer breeze on the beach while I do some pilates."
sentence2 = "I am enjoying the summer breeze on the beach while I am doing some pilates."
< /code>
Erwartete Ergebnisse (das durch Sternchen gekennzeichnete Teil sollte rot sein): < /p>
 I *am* enjoying the summer breeze on the beach while I *am doing* some pilates.
< /code>
Beispiel 2: < /p>
sentence1: "My favourite season is Autumn while my sister's favourite season is Winter."
sentence2: "My favourite season is Autumn, while my sister's favourite season is Winter."
< /code>
Erwartete Ergebnisse (das Komma ist unterschiedlich): < /p>
"My favourite season is Autumn*,* while my sister's favourite season is Winter."
< /code>
Ich habe dies ausprobiert: < /p>
sentence1 = "I'm enjoying the summer breeze on the beach while I do some pilates."
sentence2 = "I'm enjoying the summer breeze on the beach while I am doing some pilates."

# Split the sentences into words
words1 = sentence1.split()
words2 = sentence2.split()

# Find the index where the sentences differ
index_of_difference = next((i for i, (word1, word2) in enumerate(zip(words1, words2)) if word1 != word2), None)

# Highlight differing part "am doing" in red
highlighted_words = []
for i, (word1, word2) in enumerate(zip(words1, words2)):
if i == index_of_difference:
highlighted_words.append('\033[91m' + word2 + '\033[0m')
else:
highlighted_words.append(word2)

highlighted_sentence = ' '.join(highlighted_words)
print(highlighted_sentence)

< /code>
Und ich habe Folgendes erhalten: < /p>
I'm enjoying the summer breeze on the beach while I *am* doing some
< /code>
Anstelle dessen: < /p>
I'm enjoying the summer breeze on the beach while I *am doing* some pilates.
Wie kann ich das lösen?

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post