0
votes

Utilisation du module de Python pour remplacer toutes les ponctuations de deux cordes pour les comparer?

import re
def compare_strings(string1, string2):
  #Convert both strings to lowercase 
  #and remove leading and trailing blanks
  string1 = string1.lower().strip()
  string2 = string2.lower().strip()

  #Ignore punctuation
  punctuation = r"[.?!,;:-']"
  string1 = re.sub(punctuation, r"", string1)
  string2 = re.sub(punctuation, r"", string2)

  return string1 == string2

print(compare_strings("Have a Great Day!", "Have a great day?")) # Should be True
print(compare_strings("It's raining again.", "its raining, again")) # Should be True
print(compare_strings("Learn to count: 1, 2, 3.", "Learn to count: one, two, three.")) # Should be False
print(compare_strings("They found some body.", "They found somebody.")) # Should be False
The function above is removes trailing space, all punctuations from two strings and then it uses the .lower() function to remove nay capitalizations.The purpose of the function is to compare the content matter in two given strings and return True if they match or False if they don't match. There is a mistake in here which I cannot spot.

2 commentaires

Mettez le trait d'union au début des caractères de ponctuation, sinon vous pourriez obtenir une erreur de mauvaise portée. Le trait d'union est utilisé pour spécifier des gammes de caractères (comme a-z ), il a donc besoin d'une manipulation spéciale.


Le dernier exemple est génial!


4 Réponses :


1
votes

Il suffit d'échapper au symbole - . r "[.?!,;: \ - ']" devrait fonctionner. Vous devriez envisager de rédiger votre regex dans un ex validateur ex. REGEX101


0 commentaires

1
votes

Puisque la question semble être à propos de ce cas particulier, je vais fournir une approche alternative.

for ch in ".?!,;:-'": 
    string.replace(ch,"")


0 commentaires

0
votes
punctuation = r"[.?!,;:'-]"

0 commentaires

0
votes
import re
def compare_strings(string1, string2):
    #Convert both strings to lowercase
    #and remove leading and trailing blanks
    string1 = string1.lower().strip()
    string2 = string2.lower().strip()

    #Ignore punctuation
    punctuation = r"[.?!,;:\-']"
    string1 = re.sub(punctuation, r"", string1)
    string2 = re.sub(punctuation, r"", string2)

    #DEBUG CODE GOES HERE
    print(string1, "==", string2)

    return string1 == string2

print(compare_strings("Have a Great Day!", "Have a great day?")) # True
print(compare_strings("It's raining again.", "its raining, again")) # True
print(compare_strings("Learn to count: 1, 2, 3.", "Learn to count: one, two, three.")) # False
print(compare_strings("They found some body.", "They found somebody.")) # False

0 commentaires