Đoạn mã bằng Python để trích lọc tiếng Việt từ dạng HTML sang dạng văn bản thông thường. Thay đường dẫn đến thư mục chứa các file HTML vào biến path và chạy mã. Kết quả sẽ được lưu vào file corpus.txt. #!/usr/bin/python # -*- coding: utf8 -*- import os import re, htmlentitydefs import html2text import nltk import codecs import string cdau = u"àảãáạăằẳẵắặâầẩẫấậèẻẽéẹêềểễếệìỉĩíịòỏõóọôồổỗốộơờởỡớợùủũúụưừửữứựỳỷỹýỵđÀẢÃÁẠĂẰẲẴẮẶÂẦẨẪẤẬÈẺẼÉẸÊỀỂỄẾỆÌỈĨÍỊÒỎÕÓỌÔỒỔỖỐỘƠỜỞỠỚỢÙỦŨÚỤƯỪỬỮỨỰỲỶỸÝỴĐ" path = "" #thư mục chứa các file HTML FJoin = os.path.join files = [FJoin(path, f) for f in os.listdir(path)] def unescape(text): """ Removes HTML or XML character references and entities from a text string. @param text The HTML (or XML) source text. @return The plain text, as a Unicode string, if necessary. """ def fixup(m): text = m.group(0) if text[:2] == "&#": # character reference try: if text[:3] == "&#x": return unichr(int(text[3:-1], 16)) else: return unichr(int(text[2:-1])) except ValueError: pass else: # named entity try: text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]) except KeyError: pass return text # leave as is return re.sub("&#?\w+;", fixup, text) def VNESE(str): #hàm kiểm tra tiếng Việt bằng cách đếm dấu count = 0 for char in str : if char in cdau : count += 1 if count * 1.0 > 0.1 * len(str) : return True else : return False wordseg = re.compile('(\w+|\S+)',re.U) fo = codecs.open("corpus.txt","w","utf8") corpus = set() for file in files : fi = codecs.open(file, "r", "utf8") try : html = fi.read() except : print "Can't open file " + file continue fi.close() begin_post = html.find("<body") #chỉ lấy tiếng Việt trong thẻ body end_post = html.find("/body>") text = html[begin_post : end_post] text = nltk.clean_html(text) text = unescape(text) #lines = text.split("\n") #text = " ".join(text.split()) seg = text.split("\n") for lines in seg : for line in lines.split(". ") : if VNESE(line) : line = " ".join(line.split()) if line not in corpus : fo.writelines(line + ".\n") corpus.add(line) print len(corpus) fo.close() |
Các công cụ xử lý >