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

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

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


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

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

解决方案:

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


当前回答

在寻找不同的解决方案时,我发现

https://code.google.com/p/ude/

这个溶液有点重。

我需要一些基本的编码检测,基于4个第一个字节和可能的xml字符集检测-所以我从互联网上取了一些样本源代码,并添加了稍微修改的版本

http://lists.w3.org/Archives/Public/www-validator/2002Aug/0084.html

为Java编写的。

    public static Encoding DetectEncoding(byte[] fileContent)
    {
        if (fileContent == null)
            throw new ArgumentNullException();

        if (fileContent.Length < 2)
            return Encoding.ASCII;      // Default fallback

        if (fileContent[0] == 0xff
            && fileContent[1] == 0xfe
            && (fileContent.Length < 4
                || fileContent[2] != 0
                || fileContent[3] != 0
                )
            )
            return Encoding.Unicode;

        if (fileContent[0] == 0xfe
            && fileContent[1] == 0xff
            )
            return Encoding.BigEndianUnicode;

        if (fileContent.Length < 3)
            return null;

        if (fileContent[0] == 0xef && fileContent[1] == 0xbb && fileContent[2] == 0xbf)
            return Encoding.UTF8;

        if (fileContent[0] == 0x2b && fileContent[1] == 0x2f && fileContent[2] == 0x76)
            return Encoding.UTF7;

        if (fileContent.Length < 4)
            return null;

        if (fileContent[0] == 0xff && fileContent[1] == 0xfe && fileContent[2] == 0 && fileContent[3] == 0)
            return Encoding.UTF32;

        if (fileContent[0] == 0 && fileContent[1] == 0 && fileContent[2] == 0xfe && fileContent[3] == 0xff)
            return Encoding.GetEncoding(12001);

        String probe;
        int len = fileContent.Length;

        if( fileContent.Length >= 128 ) len = 128;
        probe = Encoding.ASCII.GetString(fileContent, 0, len);

        MatchCollection mc = Regex.Matches(probe, "^<\\?xml[^<>]*encoding[ \\t\\n\\r]?=[\\t\\n\\r]?['\"]([A-Za-z]([A-Za-z0-9._]|-)*)", RegexOptions.Singleline);
        // Add '[0].Groups[1].Value' to the end to test regex

        if( mc.Count == 1 && mc[0].Groups.Count >= 2 )
        {
            // Typically picks up 'UTF-8' string
            Encoding enc = null;

            try {
                enc = Encoding.GetEncoding( mc[0].Groups[1].Value );
            }catch (Exception ) { }

            if( enc != null )
                return enc;
        }

        return Encoding.ASCII;      // Default fallback
    }

从文件中读取1024字节就足够了,但我加载的是整个文件。

其他回答

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

遇到了同样的问题,但还没有找到一个自动检测的好解决方案。 现在我使用PsPad (www.pspad.com)为那;)工作正常

notepad++具有这个功能。它还支持对其进行更改。

在寻找不同的解决方案时,我发现

https://code.google.com/p/ude/

这个溶液有点重。

我需要一些基本的编码检测,基于4个第一个字节和可能的xml字符集检测-所以我从互联网上取了一些样本源代码,并添加了稍微修改的版本

http://lists.w3.org/Archives/Public/www-validator/2002Aug/0084.html

为Java编写的。

    public static Encoding DetectEncoding(byte[] fileContent)
    {
        if (fileContent == null)
            throw new ArgumentNullException();

        if (fileContent.Length < 2)
            return Encoding.ASCII;      // Default fallback

        if (fileContent[0] == 0xff
            && fileContent[1] == 0xfe
            && (fileContent.Length < 4
                || fileContent[2] != 0
                || fileContent[3] != 0
                )
            )
            return Encoding.Unicode;

        if (fileContent[0] == 0xfe
            && fileContent[1] == 0xff
            )
            return Encoding.BigEndianUnicode;

        if (fileContent.Length < 3)
            return null;

        if (fileContent[0] == 0xef && fileContent[1] == 0xbb && fileContent[2] == 0xbf)
            return Encoding.UTF8;

        if (fileContent[0] == 0x2b && fileContent[1] == 0x2f && fileContent[2] == 0x76)
            return Encoding.UTF7;

        if (fileContent.Length < 4)
            return null;

        if (fileContent[0] == 0xff && fileContent[1] == 0xfe && fileContent[2] == 0 && fileContent[3] == 0)
            return Encoding.UTF32;

        if (fileContent[0] == 0 && fileContent[1] == 0 && fileContent[2] == 0xfe && fileContent[3] == 0xff)
            return Encoding.GetEncoding(12001);

        String probe;
        int len = fileContent.Length;

        if( fileContent.Length >= 128 ) len = 128;
        probe = Encoding.ASCII.GetString(fileContent, 0, len);

        MatchCollection mc = Regex.Matches(probe, "^<\\?xml[^<>]*encoding[ \\t\\n\\r]?=[\\t\\n\\r]?['\"]([A-Za-z]([A-Za-z0-9._]|-)*)", RegexOptions.Singleline);
        // Add '[0].Groups[1].Value' to the end to test regex

        if( mc.Count == 1 && mc[0].Groups.Count >= 2 )
        {
            // Typically picks up 'UTF-8' string
            Encoding enc = null;

            try {
                enc = Encoding.GetEncoding( mc[0].Groups[1].Value );
            }catch (Exception ) { }

            if( enc != null )
                return enc;
        }

        return Encoding.ASCII;      // Default fallback
    }

从文件中读取1024字节就足够了,但我加载的是整个文件。

如果有人在寻找一个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();
        }
    }
}