我编写了一个 beautifulsoup 脚本,可以抓取日语 HTML。一切似乎都正常,我收到零错误消息。当我打印时我得到:
連鎖に打ち勝たねばならない」と述べ拍手を浴び etc
但是在同一个脚本中,当我将输出保存在 csv 中时,我得到:
\u5ddd\u3001\u6ce2\u4f50\u5834\uff13\u7279\u6d3e\u54e1\u304c\u8a71\u3057\u5408 etc
我认为问题出在代码的写入 csv 部分,但我不知道该怎么做。
代码如下:
def processData( pageFile ):
f = open(pageFile, "r")
page = f.read()
f.close()
soup = BeautifulSoup(page, 'html.parser')
metaData = soup.find_all("div", {'class': 'detail001'})
one = [ ]
for html in metaData:
text = BeautifulSoup(str(html).strip().replace("\n", ""),features="html.parser")
text = text.get_text()
one.append(text.strip())
csvfile = open(dir2 + ".csv".encode("utf-8"), 'ab')
writer = csv.writer(csvfile)
for ones in zip(one):
writer.writerow([one])
csvfile.close()
dir1 = "/home/sveisa/"
dir2 = "test2"
dir = dir1 + dir2
csvFile = dir2 + ".csv"
csvfile = open(csvFile.encode("utf-8"), 'w')
writer = csv.writer(csvfile)
writer.writerow(["one"])
csvfile.close()
fileList = os.listdir(dir)
totalLen = len(fileList)
for htmlFile in fileList:
path = os.path.join(dir, htmlFile)
processData(path)
我使用的是 Ubuntu。
最佳答案
这是关于需要分配给您的csv
的encoding=
,如下所示:
with open("data.csv", 'w', encoding="UTF-8") as f:
writer = csv.writer(f)
writer.writerow(
"\u5ddd\u3001\u6ce2\u4f50\u5834\uff13\u7279\u6d3e\u54e1\u304c\u8a71\u3057\u5408")
输出内容:
川、波佐場3特派員が話し合
关于python - 打印时显示日语字符,但保存到 csv 时不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61170388/