Replacing multiple accented letters in string with one letter using list comprehension

md2614 :

I have a function which takes a string and has parameters for ignoring case and ignoring accents. It all seems to work when using a for loop for the ignore_accents parameter. When trying to use a list comprehension though, it no longer returns the expected value.

Is this just a syntax error? I am not able to implement the list comprehension. I've been looking at Best way to replace multiple characters in a string? and a few other posts.

def count_letter_e_text(file_text, ignore_accents, ignore_case):

    e = "e"
    acc_low_e = ["é", "ê", "è"]

    if ignore_case is True:
        file_text = file_text.lower()

    if ignore_accents is True:

        # this works
        #file_text = file_text.replace("é", e).replace("ê", e).replace("è", e)

        # this works too
#         for ch in acc_low_e:
#             if ch in file_text:
#                 file_text = file_text.replace(ch, e)

        # does not work as list comprehension
        #file_text = [ch.replace(ch, e) for ch in file_text if ch in acc_low_e] # gives count of 6
        file_text = [file_text.replace(ch, e) for ch in acc_low_e if ch in file_text] # gives count of 0

    num_of_e = file_text.count(e) 

    return num_of_e

Driver program:

text = "Sentence 1 test has e, é, ê, è, E, É, Ê, È"
# expecting count of 12; using list comprehension it is 0
text_e_count = count_letter_e_text(text, True, True)
text_e_count
Serge Ballesta :

A list comprehension produces a list. Here you could build a list of characters and join it:

file_text = ''.join([t if t not in acc_low_e else 'e' for t in file_text])

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=291414&siteId=1