【问题标题】:Trouble on Unicode encoded data in PythonPython中Unicode编码数据的问题
【发布时间】:2016-07-07 22:19:54
【问题描述】:

你好 StackOverflow 社区。​​p>

我是 Python 的一个相当新的用户,对于这个问题的愚蠢之处,我深表歉意!但是我已经尝试修复了几个小时,但仍然没有弄明白。

我正在尝试导入一个大型文本数据集以在 Python 中对其进行操作。

此数据集位于 .csv 中,由于编码问题,我在读取它时遇到了问题。

我尝试使用 notepad++ 将其编码为 UTF-8 文本 我在 Python 中尝试过 csv.reader 模块

这是我的代码示例:

import csv
with open('twitter_test_python.csv') as csvfile:
    #for file5 in csvfile:
    #    file5.readline()
    #csvfile = csvfile.encode('utf-8')
    spamreader = csv.reader(csvfile, delimiter=str(','), quotechar=str('|')
    for row in spamreader:
        row = " ".join(row)
        row2= str.split(row)
    listsw = []
    for mots in row2:
        if mots not in sw:
            del mots
    print row2

但是当我在 Python 中导入数据时,无论我使用哪种方法,我仍然存在编码问题(口音等)。

如何对我的数据进行编码,以便使用 Python 正确读取?

谢谢!

【问题讨论】:

  • 我仍然有编码问题 完全没有任何意义!说出确切发生的情况和预期的情况。
  • 这是我数据中的一个列表示例:[u"En vrai j'en ai marre j'ai une poste \xe0 3min de chez moi et le postier il d\xe9cide de mettre mon colis dans une poste que je connais pas"] .
  • 我想要那个:[En vrai j'en ai marre j'ai une poste à 3min de chez moi et le postier il décide de mettre mon colis dans une poste que je connais pas]
  • 那么,pas de problème。当我在 IDLE 上键入 print u"En vrai j'en ai marre j'ai une poste \xe0 3min de chez moi et le postier il d\xe9cide de mettre mon colis dans une poste que je connais pas" 时,我得到正确的 En vrai j'en ai marre j'ai une poste à 3min de chez moi et le postier il décide de mettre mon colis dans une poste que je connais pas。这意味着您的数据是正确的 unicode 字符串,其中包含正确的 unicode 重音字符。换句话说,您在读取数据时没有编码问题,但在显示数据时可能会遇到。

标签: python csv unicode encoding utf


【解决方案1】:

Alexey Smirnov's answer 很优雅,但对于初学者来说可能有点复杂。所以让我举一个更接近问题中代码的例子。

当您使用 Python 2 读取文件时,您会得到 str 的内容,而不是 unicode。可能您想尽快转换它。但是,documentation of the csv module 表示“此版本的 csv 模块不支持 Unicode 输入。”所以你应该编码csv.reader的输出,而不是输入。将其插入您的代码会导致:

import csv
with open('twitter_test_python.csv') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=str(','), quotechar=str('|'))
    for row in spamreader:
        row = " ".join(row)
        row = unicode(row, encoding="utf-8")
        row2 = row.split()

但是,您可能需要考虑加入单元以再次拆分它们是否真的是您想要的。没有它,代码将如下所示。如果列表元素包含空格,结果会有所不同。

import csv
with open('twitter_test_python.csv') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=str(','), quotechar=str('|'))
    for row in spamreader:
        row2 = list(unicode(cell, encoding="utf-8") for cell in row)

如果您想将某些内容写回文件,您应该首先将unicode 转换回str,例如unicode.encode("utf-8")

【讨论】:

  • 感谢您的回答。所以这意味着我可以处理数据,即使它在 Python 中看起来不太好?
  • 是的,您可以使用 python 处理 unicode。考虑到您的新 cmets,我假设您指的是 print 的输出。您可能对str() vs repr() 的不同之处感兴趣。 print 使用 str 表示。 list 使用它的 str-representation 和 repr-representation 的元素。要获得所需的输出,请使用print "[" + ", ".join(row2) + "]"
【解决方案2】:

csv模块documentation 提供了如何处理unicode的例子:

import csv,codecs,cStringIO

class UTF8Recoder:
    def __init__(self, f, encoding):
        self.reader = codecs.getreader(encoding)(f)
    def __iter__(self):
        return self
    def next(self):
        return self.reader.next().encode("utf-8")

class UnicodeReader:
    def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **kwds):
        f = UTF8Recoder(f, encoding)
        self.reader = csv.reader(f, dialect=dialect, **kwds)
    def next(self):
        '''next() -> unicode
        This function reads and returns the next line as a Unicode string.
        '''
        row = self.reader.next()
        return [unicode(s, "utf-8") for s in row]
    def __iter__(self):
        return self

class UnicodeWriter:
    def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **kwds):
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()
    def writerow(self, row):
        '''writerow(unicode) -> None
        This function takes a Unicode string and encodes it to the output.
        '''
        self.writer.writerow([s.encode("utf-8") for s in row])
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        data = self.encoder.encode(data)
        self.stream.write(data)
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

with open('twitter_test_python.csv','rb') as spamreader:
    reader = UnicodeReader(fin)
    for line in reader:
        #do stuff
        print line

【讨论】:

    猜你喜欢
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 2019-10-30
    • 1970-01-01
    • 2014-04-08
    • 2011-07-14
    • 2017-04-06
    相关资源
    最近更新 更多