我需要根据已知的文件编码和所需的输出编码决定何时(不)转换文本文件。
如果文本是US-ASCII,如果输出编码是ASCII,UTF-8,Latin1,...,我不需要转换它。 显然我需要将US-ASCII文件转换为UTF-16或UTF-32。
标准编码列表存在于 http://www.iana.org/assignments/character-sets/character-sets.xml
如果符合以下条件,则必须进行转换:
我想知道:
修改
我已经找到了问题的答案
这里:Character set that is not a superset of ASCII
相反,知道:
这看起来很有希望:
mime.charsets - list of character sets which are ASCII supersets,
但我找不到一个真正的mime.charsets文件。
答案 0 :(得分:3)
另一种方法是解码给定编码中的字节0x00 - 0x7F,并检查字符是否与ASCII匹配。例如,在Python 3.x中:
def is_ascii_superset(encoding):
for codepoint in range(128):
if bytes([codepoint]).decode(encoding, 'ignore') != chr(codepoint):
return False
return True
这给出了:
>>> is_ascii_superset('US-ASCII')
True
>>> is_ascii_superset('windows-1252')
True
>>> is_ascii_superset('ISO-8859-15')
True
>>> is_ascii_superset('UTF-8')
True
>>> is_ascii_superset('UTF-16')
False
>>> is_ascii_superset('IBM500') # a variant of EBCDIC
False
编辑:获取Qt版本在C ++中支持的每种编码的US-ASCII兼容性:
#include <QTextCodec>
#include <QMap>
typedef enum
{
eQtCodecUndefined,
eQtCodecAsciiIncompatible,
eQtCodecAsciiCompatible,
} tQtCodecType;
QMap<QByteArray, tQtCodecType> QtCodecTypes()
{
QMap<QByteArray, tQtCodecType> CodecTypes;
// How to test Qt's interpretation of ASCII data?
QList<QByteArray> available = QTextCodec::availableCodecs();
QTextCodec *referenceCodec = QTextCodec::codecForName("UTF-8"); // because Qt has no US-ASCII, but we only test bytes 0-127 and UTF-8 is a superset of US-ASCII
if(referenceCodec == 0)
{
qDebug("Unable to get reference codec 'UTF-8'");
return CodecTypes;
}
for(int i = 0; i < available.count(); i++)
{
const QByteArray name = available.at(i);
QTextCodec *currCodec = QTextCodec::codecForName(name);
if(currCodec == NULL)
{
qDebug("Unable to get codec for '%s'", qPrintable(QString(name)));
CodecTypes.insert(name, eQtCodecUndefined);
continue;
}
tQtCodecType type = eQtCodecAsciiCompatible;
for(uchar j = 0; j < 128; j++) // UTF-8 == US-ASCII in the lower 7 bit
{
const char c = (char)j; // character to test < 2^8
QString sRef, sTest;
sRef = referenceCodec->toUnicode(&c, 1); // convert character to UTF-16 (QString internal) assuming it is ASCII (via UTF-8)
sTest = currCodec->toUnicode(&c, 1); // convert character to UTF-16 assuming it is of type [currCodec]
if(sRef != sTest) // compare both UTF-16 representations -> if they are equal, these codecs are transparent for Qt
{
type = eQtCodecAsciiIncompatible;
break;
}
}
CodecTypes.insert(name, type);
}
return CodecTypes;
}