1

私は Python 3 でプログラミングしていますが、小さな問題があり、ネット上でそれへの参照が見つかりません。

デフォルトの文字列がutf-16であることを理解している限り、utf-8で作業する必要があるため、デフォルトの文字列からutf-8に変換するコマンドが見つかりません。どうもありがとうございました。

4

1 に答える 1

7

Python 3 では、文字列操作を行う際に重要な 2 つの異なるデータ型があります。まず、Unicode コード ポイントを表すオブジェクトである string クラスがあります。取得する重要な点は、この文字列がバイトではなく、実際には一連の文字であるということです。第 2 に、bytes クラスがあります。これはバイトのシーケンスであり、多くの場合、エンコーディング (utf-8 や iso-8859-15 など) で格納された文字列を表します。

これはあなたにとって何を意味しますか?私が理解している限り、あなたは utf-8 ファイルを読み書きしたいと思っています。すべての 'ć' を 'ç' 文字に置き換えるプログラムを作成してみましょう

def main():
    # Let's first open an output file. See how we give an encoding to let python know, that when we print something to the file, it should be encoded as utf-8
    with open('output_file', 'w', encoding='utf-8') as out_file:
        # read every line. We give open() the encoding so it will return a Unicode string. 
        for line in open('input_file', encoding='utf-8'):
            #Replace the characters we want. When you define a string in python it also is automatically a unicode string. No worries about encoding there. Because we opened the file with the utf-8 encoding, the print statement will encode the whole string to utf-8.
            print(line.replace('ć', 'ç'), out_file)

では、いつバイトを使用する必要がありますか? しばしばあるわけではない。私が考えることができる例は、ソケットから何かを読み取るときです。これがバイトオブジェクトにある場合は、bytes.decode('encoding') を実行して Unicode 文字列にすることができ、str.encode('encoding') を使用してその逆を行うことができます。しかし、言ったように、おそらくあなたはそれを必要としません。

それでも、興味深いので、すべてを自分でエンコードするという難しい方法があります。

def main():
    # Open the file in binary mode. So we are going to write bytes to it instead of strings
    with open('output_file', 'wb') as out_file:
        # read every line. Again, we open it binary, so we get bytes 
        for line_bytes in open('input_file', 'rb'):
            #Convert the bytes to a string
            line_string = bytes.decode('utf-8')
            #Replace the characters we want. 
            line_string = line_string.replace('ć', 'ç')
            #Make a bytes to print
            out_bytes = line_string.encode('utf-8')
            #Print the bytes
            print(out_bytes, out_file)

このトピック (文字列エンコーディング) についての良い読み物はhttp://www.joelonsoftware.com/articles/Unicode.htmlです。本当におすすめの一読!

ソース: http://docs.python.org/release/3.0.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit

(PS ご覧のとおり、この投稿では utf-16 について言及していませんでした。Python がこれを内部デコードとして使用しているかどうかは実際にはわかりませんが、まったく関係ありません。現時点では、文字列を操作しています。バイトではなく、文字 (コード ポイント) を操作します。

于 2010-06-29T11:40:02.683 に答える