python - 使用列表理解将字符串中的多个重音字母替换为一个字母

标签 python list-comprehension

我有一个函数,它接受一个字符串并具有忽略大小写和忽略重音的参数。当对 ignore_accents 参数使用 for 循环时,这一切似乎都有效。但是,当尝试使用列表理解时,它不再返回预期值。

这只是一个语法错误吗?我无法实现列表理解。我一直在看Best way to replace multiple characters in a string?以及其他一些帖子。

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

驱动程序:

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

最佳答案

列表推导式会生成一个列表。在这里您可以构建一个字符列表并加入它:

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

关于python - 使用列表理解将字符串中的多个重音字母替换为一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60707880/

相关文章:

python - 如何从 ValuesView 获取值(value)?尝试理解我的机器人的 Dialogflow 响应

Python ftplib - 有什么方法可以关闭它吗?

python - 验证密码的功能,为什么这个代码不起作用?

python - 如何对预测值进行反向移动平均(在 pandas 中,rolling().mean)操作?

python - 如何从 pandas 数据帧创建字典的字典?

coffeescript - CoffeeScript 中的列表/对象搜索

python - 如何根据 if 条件跳过 for 循环中的几次迭代?

python - 这个函数必须使用 reduce() 还是有更多的 pythonic 方式?

python - 为什么操作完成后可以访问列表理解变量?

python - 使用 if/else 和 for 循环将项目附加到列表理解中的列表