从CSV文件中读取俄语数据

6

我有一些数据存储在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

I got this error:

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

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

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


1
return ([f.decode('cp1251') if isinstance(s, bytes) else f for f in row] for row in csv.reader(open(filename, "rb"),delimiter=";")) - jfs
4个回答

12

\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。


1
抱歉,看最新的编辑。你的代码应该使用UnicodeReader() - Alastair McCormack
我在我的代码中包含了UnicodeReader和UTF8Recoder,并尝试使用loadCsv()。但是数据集变量中的数据看起来像这样:u"2-\u043a\u043e\u043c\u043d\u0430\u0442。我做错了什么吗? - Erba Aitbayev
1
不,没关系。这是因为您正在打印整行代码,它是一个列表,因此您会得到一个“表示形式”。您所看到的是Unicode文字,这意味着您的数据已经被正确解码。这是一件好事! :)尝试执行print line[0],这将把Unicode值编码为您的控制台区域设置 - Alastair McCormack
1
我已经添加了一些代码来展示如何迭代和连接您的结果。 - Alastair McCormack
1
啊,是的。我明白为什么会发生那种情况。我已经更新了loadCsv方法以返回一些东西。 - Alastair McCormack
花了三个多小时,这很有帮助,但是我直接像这样从csv文件中读取,使用Windows编码建议如下:pd.read_csv('data.csv', sep=';', encoding='windows-1251') - data_runner

6

你可以尝试以下方法:

import pandas as pd 
pd.read_csv(path_file , "cp1251")

或者

import csv
with open(path_file,  encoding="cp1251", errors='ignore') as source_file:
        reader = csv.reader(source_file, delimiter=",") 

2

你的 .csv 文件是否可以使用其他编码方式,而非 UTF-8?(考虑到错误信息,它甚至应该是其他编码方式)。尝试使用其他西里尔文编码方式,例如 Windows-1251、CP866 或 KOI8。


0
在 Python 3 中:
import csv

path = 'C:/Users/me/Downloads/sv.csv'

with open(path, encoding="UTF8") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接