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