2012-01-06 42 views
1

我相信英文.txt是Latin-1,但它可能包含另一種編碼的片段。是否有庫或工具來定位這些碎片?在非拉丁文-1文件中查找非拉丁文文本的片段?

我知道諸如Python chardat庫之類的東西,但我特別想找一個工具來測試Latin-1文件並檢測異常。即使是一個普通的檢測庫也可以,如果它能告訴我檢測到一個非拉丁-1模式的位置並給我索引。

特別歡迎命令行工具和Python庫。

+0

我覺得你的痛苦,你有沒有試過像[ENCA(http://linux.die.net/man/1/enca)? – Gleno 2012-01-06 09:04:07

+0

恩卡看起來很完美,但奇怪的是,它似乎並不支持英語。只是一堆東歐語言。真的很奇怪,因爲英語裏有大量的文檔。 – Alex 2012-01-06 10:04:53

+0

你能舉出異常的例子嗎?你在尋找UTF8還是其他一些8位字符集?代碼點0x80-0x9F在拉丁文中是未定義的,否則所有序列都是有效的。如果你正在尋找像拉丁文混合的KOI-8r,lettter頻率和n-gram字母序列是一個很好的啓發式,但是無法確切地知道每個單獨的字符。 – tripleee 2012-01-06 10:07:14

回答

0

Latin-1(或者你的意思是它的歐元符號拉丁文-15變體?)不容易檢測到。

簡單的方法可能是檢查是否有一些未使用的字符實際上正在使用 (請參閱表here) - 如果有,某些錯誤。然而,爲了檢測更微妙的違規行爲,需要實際檢查該語言是否是拉丁語-1所使用的語言之一。否則,無法區分8位編碼。它更好地從不混合8位編碼在第一個地方,沒有在某種方式標記編碼的變化...

0

你的信仰是什麼理由是文件(1)是Latin-1(2 )可能包含另一種編碼的片段?文件有多大?什麼是「常規檢測庫」?您是否認爲它可能是Windows編碼的可能性,例如CP1252?

一些粗線條的診斷:

# preliminaries 
text = open('the_file.txt', 'rb').read() 
print len(text), "bytes in file" 

# How many non-ASCII bytes? 
print sum(1 for c in text if c > '\x7f'), "non-ASCII bytes" 

# Will it decode as UTF-8 OK? 
try: 
    junk = text.decode('utf8') 
    print "utf8 decode OK" 
except UnicodeDecodeError, e: 
    print e 

# Runs of more than one non-ASCII byte are somewhat rare in single-byte encodings 
# of languages written in a Latin script ... 
import re 
runs = re.findall(r'[\x80-\xff]+', text) 
nruns = len(runs) 
print nruns, "runs of non-ASCII bytes" 
if nruns: 
    avg_rlen = sum(len(run) for run in runs)/float(nruns) 
    print "average run length: %.2f bytes" % avg_rlen 
# then if indicated you could write some code to display runs in context ...