我有包含html标签的文本文件,我想用Python使用html2text删除它:
import html2text
html = open("textFileWithHtml.txt").read()
print html2text.html2text(html)
我的问题是如何将输出写入.txt文件? (我想创建没有html元素的新文本文件 - 该文件以前不存在)
答案 0 :(得分:3)
您应该打开一个文件并写入它。
import html2text
# Open your file
with open("textFileWithHtml.txt", 'r') as f_html:
html = f_html.read()
# Open a file and write to it
with open('your_file.txt', 'w') as f:
f.write(html2text.html2text(html).encode('utf-8'))
最好在处理文件对象时使用with关键字。
它也更加pythonic 查看有关读/写文件的文件的更多信息:https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
修改强>
如果您遇到编码问题,请尝试使用.encode('utf-8')
。我已将其添加到我的代码剪辑中。如果您对此问题(https://docs.python.org/2/howto/unicode.html)
答案 1 :(得分:2)
您需要打开另一个文件进行写作。
import html2text
html = open("textFileWithHtml.txt")
f = html.read()
w = open("out.txt", "w")
w.write(html2text.html2text(f).encode('utf-8'))
html.close()
w.close()