我是 Python 编程新手。我在 Python 文件中使用以下代码:
import gethtml
import articletext
url = "http://www.thehindu.com/news/national/india-calls-for-resultoriented-steps-at-asem/article5339414.ece"
result = articletext.getArticle(url)
text_file = open("Output.txt", "w")
text_file.write(result)
text_file.close()
文件articletext.py
包含以下代码:
from bs4 import BeautifulSoup
import gethtml
def getArticleText(webtext):
articletext = ""
soup = BeautifulSoup(webtext)
for tag in soup.findAll('p'):
articletext += tag.contents[0]
return articletext
def getArticle(url):
htmltext = gethtml.getHtmlText(url)
return getArticleText(htmltext)
但我收到以下错误:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 473: ordinal not in range(128)
To print the result into the output file, what proper code should I write ?
The output `result` is text in the form of a paragraph.
为了解决 unicode 错误,我们需要将文本编码为 unicode(准确地说是 UTF-8)而不是 ascii。为了确保在出现编码错误时不会抛出错误,我们将忽略没有映射的任何字符。 (您还可以使用“替换”或 str.encode 提供的其他选项。请参阅此处有关 Unicode 的 Python 文档。 http://docs.python.org/2/howto/unicode.html#the-unicode-type)
打开文件的最佳实践是使用 Python 上下文管理器,即使出现错误,它也会关闭文件。我在路径中使用斜杠而不是反斜杠,以确保它可以在 Windows 或 Unix/Linux 中工作。
text = text.encode('UTF-8', 'ignore')
with open('/temp/Out.txt', 'w') as file:
file.write(text)
这相当于
text = text.encode('UTF-8', 'ignore')
try:
file = open('/temp/Out.txt', 'w')
file.write(text)
finally:
file.close()
但上下文管理器的冗长程度要低得多,并且不太可能导致您在错误期间锁定文件。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)