在我们的应用程序中,我们从不同的来源接收文本文件(.txt, .csv等)。读取时,这些文件有时包含垃圾,因为这些文件是在不同的/未知的代码页中创建的。

是否有一种方法(自动)检测文本文件的代码页?

detectEncodingFromByteOrderMarks,在StreamReader构造函数上,适用于UTF8和其他unicode标记的文件,但我正在寻找一种方法来检测代码页,如ibm850, windows1252。


谢谢你的回答,这就是我所做的。

我们收到的文件来自最终用户,他们没有关于代码页的线索。接收者也是最终用户,到目前为止,这是他们对代码页的了解:代码页存在,并且令人讨厌。

解决方案:

在记事本中打开收到的文件,查看一段乱码的文本。如果有人叫François之类的,凭你的智商你就能猜出来。 我已经创建了一个小应用程序,用户可以使用它打开文件,并输入用户知道它将出现在文件中的文本,当使用正确的代码页时。 遍历所有代码页,并显示包含用户提供的文本的解决方案的代码页。 如果多个代码页同时弹出,请用户指定更多文本。


当前回答

你有没有尝试过c#移植到Mozilla通用字符集检测器

例子来自http://code.google.com/p/ude/

public static void Main(String[] args)
{
    string filename = args[0];
    using (FileStream fs = File.OpenRead(filename)) {
        Ude.CharsetDetector cdet = new Ude.CharsetDetector();
        cdet.Feed(fs);
        cdet.DataEnd();
        if (cdet.Charset != null) {
            Console.WriteLine("Charset: {0}, confidence: {1}", 
                 cdet.Charset, cdet.Confidence);
        } else {
            Console.WriteLine("Detection failed.");
        }
    }
}    

其他回答

如果可以链接到C库,则可以使用libenca。见http://cihar.com/software/enca/。从手册页:

Enca读取给定的文本文件,或者在没有给定的情况下读取标准输入, 并使用有关他们语言的知识(必须由您支持)和 它混合了分析、统计分析、猜测和黑魔法 来确定它们的编码。

它是GPL v2。

我使用这段代码来检测Unicode和windows默认的ansi代码页时读取文件。对于其他编码,需要手动或通过编程检查内容。这可以用来保存与打开时相同编码的文本。(我使用VB.NET)

'Works for Default and unicode (auto detect)
Dim mystreamreader As New StreamReader(LocalFileName, Encoding.Default) 
MyEditTextBox.Text = mystreamreader.ReadToEnd()
Debug.Print(mystreamreader.CurrentEncoding.CodePage) 'Autodetected encoding
mystreamreader.Close()

如果有人在寻找一个93.9%的解决方案。这对我来说很管用:

public static class StreamExtension
{
    /// <summary>
    /// Convert the content to a string.
    /// </summary>
    /// <param name="stream">The stream.</param>
    /// <returns></returns>
    public static string ReadAsString(this Stream stream)
    {
        var startPosition = stream.Position;
        try
        {
            // 1. Check for a BOM
            // 2. or try with UTF-8. The most (86.3%) used encoding. Visit: http://w3techs.com/technologies/overview/character_encoding/all/
            var streamReader = new StreamReader(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), detectEncodingFromByteOrderMarks: true);
            return streamReader.ReadToEnd();
        }
        catch (DecoderFallbackException ex)
        {
            stream.Position = startPosition;

            // 3. The second most (6.7%) used encoding is ISO-8859-1. So use Windows-1252 (0.9%, also know as ANSI), which is a superset of ISO-8859-1.
            var streamReader = new StreamReader(stream, Encoding.GetEncoding(1252));
            return streamReader.ReadToEnd();
        }
    }
}

通过输入cpanm Text::Unaccent::PurePerl,这会生成一个build.log文件,在一些应用程序中显示为中文,在其他应用程序中显示为英文。cpanm是初始文本,一个合理的尝试,如果你足够幸运,在语言中有空格,是通过统计测试来比较单词的分布频率

“uchardet”工具使用每个字符集的字符频率分布模型很好地做到了这一点。更大的文件和更“典型”的文件具有更强的可信度(显然)。

在ubuntu上,你只需要apt-get install uchardet。

在其他系统上,从这里获取源代码、用法和文档:https://github.com/BYVoid/uchardet