1

ファイルエンコーディングを認識するためにchardetを使用していますが、このエラーが発生しました:

fh= open("file", mode="r")
sc= chardet.detect(fh)

Traceback (most recent call last):
  File "/home/alireza/test.py", line 19, in <module>
    sc= chardet.detect(fh)
  File "/usr/lib/python3/dist-packages/chardet/__init__.py", line 24, in detect
    u.feed(aBuf)
  File "/usr/lib/python3/dist-packages/chardet/universaldetector.py", line 65, in feed
    aLen = len(aBuf)
TypeError: object of type '_io.TextIOWrapper' has no len()

エンコーディングがわからないとファイルを開くことができません。

fh= open("file", mode="r").read()
sc= chardet.detect(fh)

Traceback (most recent call last):
  File "/home/alireza/workspacee/makecdown/test.py", line 21, in <module>
    fh= open("910.srt", mode="r").read()
  File "/usr/lib/python3.2/codecs.py", line 300, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc7 in position 34: invalid continuation byte

ファイルを開かずにchardetを使用する方法?!または開く後/開く前にファイルエンコーディングを見つける方法はありますか?

4

2 に答える 2

1

このようにファイルを開いてみてください

fh= open("file", mode="rb")

コマンドラインツール

これが機能しない場合は、chardetのコマンドラインツールを試してください。https://github.com/erikrose/chardetからの説明:

chardetには、1つ以上のファイルのエンコーディングを報告するコマンドラインスクリプトが付属しています。

% chardetect.py somefile someotherfile
somefile: windows-1252 with confidence 0.5
someotherfile: ascii with confidence 1.0
于 2012-11-21T12:42:02.840 に答える
0

直接的な答えではありませんが、Python3でどのように機能するかについての説明はhttp://getpython3.com/diveintopython3/case-study-porting-chardet-to-python-3.htmlにあります。それを研究した後、あなたは別の特定のエンコーディングを検出する方法を見つけるかもしれません。

このコードは当初、MozillaSeamonkeyから派生したものです。あなたはそこにももっと多くの情報を見つけるかもしれません。または、Seamonkeyに関連するより高度なPythonパッケージを探してください。

于 2012-11-21T15:41:40.237 に答える