python - 从 csv 中读取俄语数据

标签 python csv unicode python-2.x python-unicode

我在 CSV 文件中有一些俄语数据:

2-комнатная квартира РДТ',  мкр Тастак-3,  Аносова — Толе би;Алматы
2-комнатная квартира БГР',  мкр Таугуль,  Дулати (Навои) — Токтабаева;Алматы
2-комнатная квартира ЦФМ',  мкр Тастак-2,  Тлендиева — Райымбека;Алматы

分隔符是;符号。


我想读取数据并将其放入数组中。我尝试使用此代码读取此数据:

def loadCsv(filename):
    lines = csv.reader(open(filename, "rb"),delimiter=";" )
    dataset = list(lines)
    for i in range(len(dataset)):
        dataset[i] = [str(x) for x in dataset[i]]
    return dataset

然后我读取并打印结果:

mydata = loadCsv('krish(csv3).csv')
print mydata

输出:

[['2-\xea\xee\xec\xed\xe0\xf2\xed\xe0\xff \xea\xe2\xe0\xf0\xf2\xe8\xf0\xe0,  \xec\xea\xf0 \xd2\xe0\xf1\xf2\xe0\xea-3,  \xc0\xed\xee\xf1\xee\xe2\xe0 \x97 \xd2\xee\xeb\xe5 \xe1\xe8', '\xc0\xeb\xec\xe0\xf2\xfb'], ['2-\xea\xee\xec\xed\xe0\xf2\xed\xe0\xff \xea\xe2\xe0\xf0\xf2\xe8\xf0\xe0,  \xec\xea\xf0 \xd2\xe0\xf3\xe3\xf3\xeb\xfc,  \xc4\xf3\xeb\xe0\xf2\xe8 (\xcd\xe0\xe2\xee\xe8) \x97 \xd2\xee\xea\xf2\xe0\xe1\xe0\xe5\xe2\xe0', '\xc0\xeb\xec\xe0\xf2\xfb'], ['2-\xea\xee\xec\xed\xe0\xf2\xed\xe0\xff \xea\xe2\xe0\xf0\xf2\xe8\xf0\xe0,  \xec\xea\xf0 \xd2\xe0\xf1\xf2\xe0\xea-2,  \xd2\xeb\xe5\xed\xe4\xe8\xe5\xe2\xe0 \x97 \xd0\xe0\xe9\xfb\xec\xe1\xe5\xea\xe0', '\xc0\xeb\xec\xe0\xf2\xfb']]

我发现在这种情况下需要编解码器并尝试对这段代码做同样的事情:

import codecs
with codecs.open('krish(csv3).csv','r',encoding='utf8') as f:
    text = f.read()
print text

我遇到了这个错误:

newchars, decodedbytes = self.decode(data, self.errors)

UnicodeDecodeError: 'utf8' codec can't decode byte 0xea in position 2: invalid continuation byte

问题是什么?使用编解码器时如何在我的数据中指定分隔符? 我只想从文件中读取数据并将其放入二维数组中。

最佳答案

\eaк 的 windows-1251/cp5347 编码。因此,您需要使用windows-1251 解码,而不是UTF-8。

在 Python 2.7 中,CSV 库不正确支持 Unicode - 请参阅 https://docs.python.org/2/library/csv.html 中的“Unicode”

他们提出了一个简单的解决方法:

class UnicodeReader:
    """
    A CSV reader which will iterate over lines in the CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        f = UTF8Recoder(f, encoding)
        self.reader = csv.reader(f, dialect=dialect, **kwds)

    def next(self):
        row = self.reader.next()
        return [unicode(s, "utf-8") for s in row]

    def __iter__(self):
        return self

这将使您能够:

def loadCsv(filename):
    lines = UnicodeReader(open(filename, "rb"), delimiter=";", encoding="windows-1251" )
    # if you really need lists then uncomment the next line
    # this will let you do call exact lines by doing `line_12 = lines[12]`
    # return list(lines)

    # this will return an "iterator", so that the file is read on each call
    # use this if you'll do a `for x in x`
    return lines 

如果您尝试打印 dataset,那么您将获得列表中列表的表示,其中第一个列表是行,第二个列表是列。任何编码的字节或文字将用 \x\u 表示。要打印这些值,请执行以下操作:

for csv_line in loadCsv("myfile.csv"):
    print u", ".join(csv_line)

如果您需要将结果写入另一个文件(相当典型),您可以这样做:

with io.open("my_output.txt", "w", encoding="utf-8") as my_ouput:
    for csv_line in loadCsv("myfile.csv"):
        my_output.write(u", ".join(csv_line))

这会自动将您的输出转换/编码为 UTF-8。

关于python - 从 csv 中读取俄语数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33996461/

相关文章:

Python列表理解 - 想要避免重复评估

python - 导入 jcc,DLL 加载失败

python - 在 Google App Engine 上在线生成 CSV 文件

Java- 从 unicode 转换为 ANSI

c# - 如何 : convert unicode character representation in string to the actual unicode character

python - 操作字符 '№'

Python py2exe 一体机

python - 如何使用 OpenCV2.0 和 Python2.6 调整图像大小

postgresql - 我应该如何打开 PostgreSQL 转储文件并向其中添加实际数据?

mysql - 在 MySql 中导入 CSV 文件时使用的正确路径