【问题标题】:How do I get rid of these symbols from the text fields when reading a CSV file?读取 CSV 文件时,如何从文本字段中删除这些符号?
【发布时间】:2019-03-11 22:30:03
【问题描述】:

每次我在 Python 中打开 CSV 时,我都会不断看到这些奇怪的符号,这些符号代表文本字段中的标点符号和特殊字符。例如:

import pandas as pd
import csv
data = pd.read_csv("Test.csv", encoding="ISO-8859-1") #utf-8 encoding doesn't work
data.head()

带有文本的列将包含类似“Assassinâ\x80\x99s creed origins”的内容。

所以我猜你想知道我最初是如何创建 csv 的?

这是我使用的代码:

def updateSubs_file():
    upload_count = 0
    import csv
    location = "csvs"
    filename = "Test.csv"
    file = location + filename
    with open(file, 'w', newline='', encoding='utf-8') as file: 
        a = csv.writer(file, delimiter=',')
        headers = ["Title","Url","Author","Score"]
        a.writerow(headers)
        for sub in subStats:
            a.writerow(subStats[sub][0])
            upload_count+=1

        print(str(upload_count) + " rows have been uploaded")

updateSubs_file()

所以我可以看到在创建 csv 并打开时已经存在编码不匹配,但我最初添加了 encoding="" 参数以避免 Unicode 解码错误。这可能/可能不是我的问题的一个因素。

当我在 Python 中上传/读取 csv 时,如果您能帮我解决这些问题,我们将不胜感激。

【问题讨论】:

  • 肯定遇到了编码问题。 “utf-8 encoding doesn't work”——但您创建文件是 UTF8。因此,尝试另一种编码是否让它神奇地工作是很遥远的事情。你的问题出在其他地方。 (可能您在创建该文件之前读取的数据不是 UTF8。但我们无法确定。)

标签: python python-3.x csv python-unicode


【解决方案1】:

UTF-8 确实工作。你用 UTF-8 写的,所以用 UTF-8 解码。比如撤消不正确的ISO-8859-1解码并用utf8重新解码:

>>> s='Assassinâ\x80\x99s creed origins'.encode('iso-8859-1').decode('utf8')
'Assassin’s creed origins'

如果您在解码使用 utf8 编写的内容时遇到问题,请显示带有示例输入和输出的准确代码以重现问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 2020-10-07
    • 2010-12-15
    • 2019-07-08
    • 2013-01-02
    • 1970-01-01
    • 2019-02-18
    相关资源
    最近更新 更多