python - 写入 CSV 文件时出现 Unicode 问题

标签 python python-3.x unicode

请给我一些指导。我正在使用以下代码:

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/

相关文章:

python - 从python中的unicode字符串获取字节

go - 如何在 Golang 中将全角数字字符转换为 Ascii?

python - 按字母分割Python字符串并保留分隔符

python - 使用 Python 显示同步的 NTP 对等服务器源

python - 将包含元组列表的字典转换为列表

python - 打印写入 CSV 文件的行数

python - 连续运行脚本 X 次(一次一个)的推荐方法是什么

java - 为什么 Intellij IDEA 不显示𝔊符号?

python - 如何根据其中一列的子字符串合并 Pandas 数据框?

javascript - 如何使用 Django 获取正在 HTML 中呈现的对象的索引