یکی از کارهای منظمی که باید انجام میدادم، خواندن متنهای تارنمایی بود که امکان گرفتن متن را بسته بود. باید کد صفحهی HTML را میگرفتم و تگهای آن را حذف میکردم. به علاوه باید حروف XML/HTML آن را به ASCII تبدیل میکردم. تصمیم گرفتم با دانش مبتدیانهای که از پایتون دارم و کمی جستوجو و راهنمایی دوستان، این کار را با کدنویسی کوتاهی در پایتون انجام بدهم.
کد زیر فایلی را میخواند (اینجا input-file.html است ولی میتوان اسم و پسوند آن را نیز تغییر داد)، سپس یونیکدهای آن را به کدهای اسکی تبدیل میکند، تگهای آن را حذف میکند و آخر سر در فایل جدیدی به نام output-file.txt ذخیره میکند.
ایراد بزرگ این کد آن است که چندین بار کل متن را وارسی میکند. این یعنی استفادهی بیش از اندازه از منابع.
# -*- coding: utf-8 -*-
import re
# This file contains HTML.
file = open('input-file.html', 'r')
temp = file.read()
# Replace Some Unicodes to ASCII.
temp = temp.replace ('‘',"""'""")
temp = temp.replace ('’',"""'""")
temp = temp.replace ('“',"""\"""")
temp = temp.replace ('”',"""\"""")
temp = temp.replace ('‚',""",""")
temp = temp.replace ('′',"""'""")
temp = temp.replace ('″',"""\"""")
temp = temp.replace ('«',"""«""")
temp = temp.replace ('»',"""»""")
temp = temp.replace ('‹',"""‹""")
temp = temp.replace ('›',"""›""")
temp = temp.replace ('&',"""&""")
temp = temp.replace ('–',""" – """)
temp = temp.replace ('—',""" — """)
temp = temp.replace ('®',"""®""")
temp = temp.replace ('©',"""©""")
temp = temp.replace ('™',"""™""")
temp = temp.replace ('¶',"""¶""")
temp = temp.replace ('•',"""•""")
temp = temp.replace ('·',"""·""")
# Replace HTML tags with an empty string.
result = re.sub("<.*?>", "", temp)
print(result)
# Write the result to a new file.
file = open("output-file.txt", "w")
file.write(result)
file.close()
کد زیر بهینه شدهی کد بالاست که از کتابخانهی HTMLParser استفاده میکند. توضیح کامل دربارهی این کد و علت عدم استفاده از تابعهای string.translate یا string.maketrans در منبع شمارهی ۴ آمده است.
import re
from HTMLParser import HTMLParser
# This file contains HTML.
file = open('input-file.html', 'r')
temp = file.read()
# Replace all XML/HTML characters to ASCII ones.
temp = HTMLParser.unescape.__func__(HTMLParser, temp)
# Replace HTML tags with an empty string.
result = re.sub("<.*?>", "", temp)
# Encode the text to UTF-8 for preventing some errors.
result = result.encode('utf-8')
print(result)
# Write the result to a new file.
file = open("output-file.txt", "w")
file.write(result)
file.close()
پیام