Saltar al contenido

~ / archivo / stackoverflow / 50804061

Python - Capitalization of words as in other string

StackOverflow · python, string · ayudé
  1. Chris C pregunta +2 2018-06-11 18:35

    I have two character strings containing full names. For each name in the full name, if the name appears in the other string, I'd like to cross reference how it is capitalized in the other string. Then I'd like to substitute the way it is capitalized in the other string back into the original string.

    This is one of the attempts I've made:

    alt_name = 'John A. desmith'
    name = 'John R. DeSmith'
    
    alt_names = alt_name.split()
    for i in range(len(alt_names)):
        if alt_names[i] in name:
            alt_names[i] = re.findall(alt_names[i], name, flags=re.IGNORECASE)
    alt_names
    

    Desired result:

    John A. DeSmith

    • Miguel Ortiz yo 2018-06-11 19:07 Isn't possible to modify the original string because in python strings are immutable.
  2. Alex respuesta aceptada +1 2018-06-11 18:45

    If you don't care about preserving the number of spaces something like this will work, and probably faster than using regex:

    alt_name = 'John   A. desmith'
    name = 'John R. DeSmith'
    d = {s.lower(): s for s in name.split()}
    corrected_alt_name = ' '.join(d.get(s.lower(), s) for s in alt_name.split())
    print(corrected_alt_name)
    

    John A. DeSmith

    If you do care about spaces then you could use re.split() instead of str.split() as described here:

    import re
    corrected_alt_name = ''.join(d.get(s.lower(), s) for s in re.split(r'(\s+)', alt_name))
    print(corrected_alt_name)
    
  3. Torxed respuesta 2018-06-11 18:44

    Not entirely sure I follow what criteria's need to be met in order for your desired result to occur.

    But I'd begin by creating the dictionary of correct words:

    name = 'John R. DeSmith'
    collection = {}
    for part in name.split():
        collection[part.lower()] = part
    

    The dictionary is extremely rudimentary and will only match against identical matches based on matching lower-case strings against each other.

    Then you can start to cross-reference each individual part of the name you put "in to it".

    alt_name = 'John A. desmith'
    
    correct_spelling = []
    for part in alt_name.split():
        if part.lower() in collection:
            correct_spelling.append(collection[part.lower()])
        else:
            correct_spelling.append(part)
    
    print('Correctly spelled: {}'.format(' '.join(correct_spelling)))
    

    There's other ways to match individual parts or the entire string, one example is by doing a Levenshtein distance comparison.

    distance('Levenshtein', 'Levenshten')
    

    Will result in a 1, meaning the two words are off by 1 character. Use that if you need to do simple spelling checks against your matches above.

  4. Rakesh respuesta 2018-06-11 18:51

    This is one approach.

    import re
    alt_name = 'John A. desmith'
    name = 'John R. DeSmith'
    
    def caps(alt_name, name):
        list_alt_name = alt_name.split()
        for i, value in enumerate(list_alt_name):
            m = re.search(r"\b{0}\b".format(value), name, flags=re.IGNORECASE)
            if m:
                list_alt_name[i] = m.group(0)
        return  " ".join(list_alt_name)
    
    print( caps(alt_name, name) )
    

    Output:

    John A. DeSmith
    
  5. Miguel Ortiz yo respuesta 2018-06-11 19:02

    To clarify: Isn't possible to modify the original string because in python strings are immutable.

    Having that in mind, this script is designed to preserve the different value in "name" (when different) from alt_name:

    alt_name = 'John A. desmith'.split()
    name = 'john R. DeSmith'.split()
    

    We preserve "R." from "name" :

    #!/usr/bin/python
    alt_name = 'John A. desmith'.split()
    name = 'john R. DeSmith'.split()
    newName=[]
    
    for i in range(0,len(name)) :
        if name[i].lower() == alt_name[i].lower() :
            newName.append(name[i].capitalize())
        else :
            newName.append(name[i].capitalize())
    
    print ' '.join(newName)
    

    Output:

    mortiz@florida:~/Documents/projects/python$ python string_names.py 
    John R. Desmith
    

    If you want to preserve the value of "A." in "alt_name" just change:

        else :
            newName.append(alt_name[i].capitalize())
    

    Output:

    mortiz@florida:~/Documents/projects/python$ python string_names.py 
    John A. Desmith
    

← todos los hilos de StackOverflow