I am trying to read Thai website with code tis-620 and convert the result to utf-8, so i could upload to any database.
I am noticed following behavior of beautifulsoup.
Simple example
Source:
"""http-equiv="Content-Type" content="text/html; charset=windows-874"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-874" />
<meta name="description" content="Discussion Forum" />
</head>
<body>
hello
<dl>
<dt>no English Thai abbrev. phonemic</dt>
<dt>01 January มกราคม ม.ค. mohkH gaL raaM khohmM</dt>
<dt>02 February กุมภาพันธ์ ก.พ. goomM phaaM phanM</dt>
<dt>03 March มีนาคม มี.ค. meeM naaM khohmM</dt>
<dt>04 April เมษายน เม.ย. maehM saaR yohnM</dt>
<dt>05 May พฤษภาคม พ.ค. phreutH saL phaaM khohmM</dt>
<dt>06 June มิถุนายน มิ.ย. miH thooL naaM yohnM</dt>
<dt>07 July กรกฎาคม ก.ค. gaL raH gaL daaM khohmM</dt>
<dt>08 August สิงหาคม ส.ค. singR haaR khohmM</dt>
<dt>09 September กันยายน ก.ย. ganM yaaM yohnM</dt>
<dt>10 October ตุลาคม ต.ค. dtooL laaM khohmM</dt>
<dt>11 November พฤศจิกายน พ.ย. phreutH saL jiL gaaM yohnM</dt>
<dt>12 December ธันวาคม ธ.ค. thanM waaM khohmM</dt>
</dl>
</body>
</html>
Python pgm:
1. example
import urllib2
from bs4 import BeautifulSoup
from datetime import date
import sys
sys.setdefaultencoding("tis-620")
reload(sys)
fthai = open('translation_thai.html','r')
soup = BeautifulSoup(fthai.read())
ln = soup.findAll('dl')
translation=[]
dttag = ln[0].findNext('dt')
for el in dttag.nextSiblingGenerator():
if el <> u'\n':
ss = el.get_text()
vsep = el.get_text().encode('utf8').split('\t')
line=[]
for x in range(0,3):
line.append(vsep[x])
translation.append(line)
fthai.close()
ss returns u'03\tMarch\t\xc1\xd5\xb9....
vsep returns ['03','March','\xc3\x81\xc3......
what is wrong according to the utf8 table
2. example without beautifulsoup
import urllib2
import sys
sys.setdefaultencoding("tis-620")
reload(sys)
fthai = open('translation_thai.html','r')
array = []
x=-1
for line in fthai:
x=x+1
array.append( line )
print array[x],x
sp = array[17].split('\t')
sp1 = sp[2].encode('utf8')
sp returns [' 03','March','\xc1\xd5\xb9......
sp1 returns '\xe0\xb8\xa1\xe0\xb8\xb5
correct!
according to utf8 table
3617 e21 ม E0B8A1 1110 0000 1011 1000 1010 0001 ม
3637 e35 ี E0B8B5 1110 0000 1011 1000 1011 0101 ี
Does anybody has a tip how I could fix the wrong behavior.