リストの内包表記を使用して1つの文字で文字列内の複数のアクセント付きの文字を置き換えます

md2614:

私は、文字列を受け取り、ケースを無視し、アクセントを無視するためのパラメータを持っている機能を持っています。使用している場合それはすべての作業に思えるforためのループignore_accentsパラメータを。けれども、リストの内包表記を使用しようと、それはもはやリターンの期待値。

これは単なる構文エラーですか?私は、リスト内包を実装することはできませんよ。私が見てきた文字列に複数の文字を置換するための最良の方法?そして、いくつかの他の記事。

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
セルジュBallestaの:

リストの内包は、リストを生成します。ここでは、文字のリストを作成し、それに参加することができます:

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

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=292486&siteId=1