質問

いUnicodeの文字列Pythonでは、どのようなすべて削除し、アクセント(diacritics).

このウェブで優雅ないこJava:

  1. 変換のUnicode文字列をその長正規化された形式(別の文字を文字とdiacritics)
  2. すべての文字をUnicodeのタイプが"diacritic".

いただいた設置、図書室などpyICU※この記事のオリジナルはこの可能性をpython標準のですか?何をpython3?

重要な注意:うなコードで明示的マッピングからのアクセント付きの文字がそのアクセント。

役に立ちましたか?

解決

のは、このための正しい答えです。これは、ASCIIテキスト内の最も近い可能表現に任意のUnicode文字列をtransliteratesます。

例:

accented_string = u'Málaga'
# accented_string is of type 'unicode'
import unidecode
unaccented_string = unidecode.unidecode(accented_string)
# unaccented_string contains 'Malaga'and is of type 'str'

他のヒント

これはどうます:

import unicodedata
def strip_accents(s):
   return ''.join(c for c in unicodedata.normalize('NFD', s)
                  if unicodedata.category(c) != 'Mn')

これは、あまりにも、ギリシャ文字で動作します:

>>> strip_accents(u"A \u00c0 \u0394 \u038E")
u'A A \u0394 \u03a5'
>>> 

文字カテゴリの "Mnは" のUnicodeDataに似ている、Nonspacing_Markの略(それはより明確なので、私はunicodedata.combining考えていなかったが、それはおそらくより良い解決策である)MiniQuarkの答えに.combiningます。

と心に留めておく、これらの操作は大幅にテキストの意味を変更することができます。アクセント、ウムラウトなど「装飾」ではありません。

私はWeb上でこの答えを見つけます:

import unicodedata

def remove_accents(input_str):
    nfkd_form = unicodedata.normalize('NFKD', input_str)
    only_ascii = nfkd_form.encode('ASCII', 'ignore')
    return only_ascii
これは、いくつかの言語のために失敗するので、

(ギリシャ例えば、)、それは(例えば、フランス語の)正常に動作しますが、私は第二のステップは、(アクセントの除去)非ASCII文字を落とすよりも優れて処理することができると思います。最善の解決策は、おそらく、明示的に発音区別符号であるとしてタグ付けされたUnicode文字を削除することです。

編集:これはトリックを行います:

import unicodedata

def remove_accents(input_str):
    nfkd_form = unicodedata.normalize('NFKD', input_str)
    return u"".join([c for c in nfkd_form if not unicodedata.combining(c)])
文字unicodedata.combining(c)は、直前の文字と組み合わせることができる場合は、

cそれは分音だ場合には、主に、trueを返します。

のの編集2:remove_accentsのユニコードの文字列ではなく、バイト文字列を期待しています。あなたがバイト文字列を持っている場合は、このようなUnicode文字列にそれをデコードする必要があります。

encoding = "utf-8" # or iso-8859-15, or cp1252, or whatever encoding you use
byte_string = b"café"  # or simply "café" before python 3.
unicode_string = byte_string.decode(encoding)

実際に働いているプロジェクトに対応python2.6,2.7 3.4としていますの作成Idから無料ユーザーのための助言を行います。

おかげさまで、創造している機能の動作ります。

import re
import unicodedata

def strip_accents(text):
    """
    Strip accents from input String.

    :param text: The input string.
    :type text: String.

    :returns: The processed String.
    :rtype: String.
    """
    try:
        text = unicode(text, 'utf-8')
    except (TypeError, NameError): # unicode is a default on python 3 
        pass
    text = unicodedata.normalize('NFD', text)
    text = text.encode('ascii', 'ignore')
    text = text.decode("utf-8")
    return str(text)

def text_to_id(text):
    """
    Convert input text to id.

    :param text: The input string.
    :type text: String.

    :returns: The processed String.
    :rtype: String.
    """
    text = strip_accents(text.lower())
    text = re.sub('[ ]+', '_', text)
    text = re.sub('[^0-9a-zA-Z_-]', '', text)
    return text

結果:

text_to_id("Montréal, über, 12.89, Mère, Françoise, noël, 889")
>>> 'montreal_uber_1289_mere_francoise_noel_889'

このだけでなくアクセントでなく、「ストローク」を扱う(としてのφなど。):

import unicodedata as ud

def rmdiacritics(char):
    '''
    Return the base character of char, by "removing" any
    diacritics like accents or curls and strokes and the like.
    '''
    desc = ud.name(unicode(char))
    cutoff = desc.find(' WITH ')
    if cutoff != -1:
        desc = desc[:cutoff]
    return ud.lookup(desc)

これは、私は、それは確かに非常にエレガントであるとは思いませんが、私は考えることができる(そしてそれは、このページのコメントにアレクシスで言及されている)で最もエレガントな方法である。

このようになって反転文字としてこれによって処理されていない特殊な文字は、そのユニコード名は「で」が含まれていないため、まだあります。それはあなたが、とにかく何をしたいかに依存します。私は時々辞書のソート順を実現するためのストリッピングアクセントを必要とします。

@ MiniQuarkの答えに対応してます:

私はハーフフランス語(アクセントを含む)であったとも最終的には、整数と浮動小数点数になるであろういくつかの文字列をCSVファイルを読み込むしようとしていました。 テストとして、私はこのように見えたtest.txtファイルを作成します:

  

モントリオール、ユーバー、12.89、単なる、フランソワーズ、ノエル、889

私は(私はPythonのチケットで見つかった)、それは仕事を得るために23行を含めるだけでなく、ジャバさんのコメント@組み込む必要がありました。

import sys 
reload(sys) 
sys.setdefaultencoding("utf-8")
import csv
import unicodedata

def remove_accents(input_str):
    nkfd_form = unicodedata.normalize('NFKD', unicode(input_str))
    return u"".join([c for c in nkfd_form if not unicodedata.combining(c)])

with open('test.txt') as f:
    read = csv.reader(f)
    for row in read:
        for element in row:
            print remove_accents(element)

結果:

Montreal
uber
12.89
Mere
Francoise
noel
889

(注:私は、Mac OS X 10.8.4の午前とPython 2.7.3を使用して)

gensim.utils.deaccent(文字) から Gensim話題のモデリングのための人:

deaccent("Šéf chomutovských komunistů dostal poštou bílý prášek") 'Sef chomutovskych komunistu dostal postou bily prasek'

少し値段が高くなりますが、 unidecode.

ということがありませんが液 unicodedata 一般的に削除アクセントでも大文字(例:ので 'ł''', ではなく 'l').

一部の言語は、アクセントを指定するには、言語の文字とアクセントの付加記号として付加記号を組み合わせています。

私はあなたがストリップしたいdiactrics明示的に指定するよりも安全だと思います:

def strip_accents(string, accents=('COMBINING ACUTE ACCENT', 'COMBINING GRAVE ACCENT', 'COMBINING TILDE')):
    accents = set(map(unicodedata.lookup, accents))
    chars = [c for c in unicodedata.normalize('NFD', string) if c not in accents]
    return unicodedata.normalize('NFC', ''.join(chars))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top