请给我一些指导。我正在使用以下代码:
import requests
import bs4
import csv
results = requests.get('http://grad-schools.usnews.rankingsandreviews.com/best-graduate-schools/top-engineering-schools/eng-rankings?int=a74509')
reqSoup = bs4.BeautifulSoup(results.text, "html.parser")
i = 0
schools = []
for school in reqSoup:
x = reqSoup.find_all("a", {"class" : "school-name"})
while i < len(x):
for name in x:
y = x[i].get_text()
i += 1
schools.append(y)
with open('usnwr_schools.csv', 'wb') as f:
writer = csv.writer(f)
for y in schools:
writer.writerow([y])
我的问题是,长破折号在生成的 CSV 文件中显示为 utf-8。我尝试了几种不同的方法来修复它,但似乎没有任何效果(包括 attempting to use regex 来摆脱它,以及尝试几年前的 .translate method that I found in a StackOverflow 问题)。
我错过了什么?我希望 csv 结果只包含文本,减去破折号。
我使用的是 Python 3.5,而且对 Python 还很陌生。
最佳答案
要删除破折号,请尝试 y.replace("—","-").replace("–","-")
(第一个是破折号到减号,第二个是是破折号到减号)
如果您只想要 ASCII 代码点,您可以使用以下命令删除其他所有内容
import string
whitelist=string.printable+string.whitespace
def clean(s):
return "".join(c for c in s if c in whitelist)
(这仅对纯英文文本产生大部分合理的结果)
顺便说一下尝试使用
open('usnwr_schools.csv', 'w', newline='', encoding='utf-8') # or whatever encoding you like
因为在 Python 3 中 csv.writer
不像 Python 2 那样采用二进制文件(您以二进制模式打开它 ("wb"
))
关于python - 写入 CSV 文件时出现 Unicode 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39600483/