多年来,我在使用Python中的Unicode时遇到了很多困难,因为我使用了许多日语文本文件,所以我很熟悉使用.encode(“utf-8”)将日语文本从u'xxxx转换回日语显示。我没有收到任何编码/解码错误。但是我从unicode文件中读取的文本,经过操作,然后写回一个新的文件,被表示为u'xxxx的字符串,而不是原来的日语文本。我在多个地方尝试了.encode()和.decode(),但也没有使用它们,每次都得到相同的结果。欢迎提出任何建议。在
具体地说,我正在使用Scrapy库编写一个spider,它从它爬行的文件中获取文本,提取一些文本来构造新文件的文件名,然后将HTML文件的第一个div作为字符串写入到新文件中。在
更让我困惑的是,我用来创建文件名的文本部分都是日文的,文件名本身也是如此。是因为我在div上使用str(),所以我得到了u'xxxx作为文件的内容吗?请在代码末尾看到这一行。在
以下是我的完整代码(请忽略其中一些代码有多粗糙):
def parse_item(self, response):
original = 0
author = "noauthor"
title = "notitle"
year = "xxxx"
publisher = "xxxx"
typer = "xxxx"
ispub = 0
filename = response.url.split("/")[-1]
if "_" in filename:
filename = filename.split("_")[0]
if filename.isdigit():
title = response.xpath("//h1/text()").extract()[0].encode("utf-8")
author = response.xpath("//h2/text()").extract()[0].encode("utf-8")
ID = filename
bibliographic_info = response.xpath("//div[2]/text()").extract()
for subyear in bibliographic_info:
ispub = 0
subyear = subyear.encode("utf-8").strip()
if "初出:" in subyear:
publisher = subyear.split(":")[1]
original = 1
ispub = 1
if "入力:" in subyear:
typer = subyear.split(":")[1]
if len(subyear) > 1 and (original == 1) and (ispub == 0):
counter = 0
while counter < len(subyear):
if subyear[counter].isdigit():
break
counter+=1
if counter != len(subyear):
year = subyear[counter:(counter+4)]
original = 0
body = str(response.xpath("//div[1]/text()").extract())
new_filename = author + "_" + title + "_" + publisher + "_" + year + "_" + typer + ".html"
file = open(new_filename, "a")
file.write(body.encode("utf-8")
file.close()
不要将
str()
与Unicode字符串一起使用作为参数,而是使用显式的.encode()
。 除非有必要,否则不要调用.encode()
,.decode()
;请改用Unicode三明治:第一步和最后一步可能是隐式的,也就是说,您的程序可能只看到Unicode文本。在
注意,这是三个不同的东西:
repr()
,'backslashreplace'错误处理程序)如果在输出中看到}被调用。它可能是隐式的,例如,通过
^{pr2}$u'...'
;这意味着在某个时刻{print([unicode_string])
,因为在将列表项转换为字符串时,repr()
被调用。在相关问题 更多 >
编程相关推荐