在Python 2.7中转换为ascii或string

时间:2016-05-27 08:19:13

标签: python python-2.7 csv encoding

我正在阅读并将csv文件解析为字典。但是,其中一个值是此'\xe2\x80\x94'而不是此'-'。如何将值转换为正确的格式? type('\xe2\x80\x94')因为引号而说它是一个字符串,但在文件中它是一个连字符。

import os

DATADIR = ""
DATAFILE = "beatles-diskography.csv"

def parse_file(datafile):
   data = list()
   with open(DATAFILE, 'rb') as f:
       header = f.readline().rstrip().split(',')

   for line in f:
       lst = list()
       line = line.rstrip().split(',')
       if len(line) > 7:
           line[2] = line[2] + ", " + line[3]
           del line[3]
       for i in range(len(line)):
            t = header[i],line[i]
            lst.append(t)

       data.append(dict(lst))

    return data

def test():
    # a simple test of your implemetation
    datafile = os.path.join(DATADIR, DATAFILE)
    d = parse_file(datafile)
    firstline = {'Title': 'Please Please Me', 'UK Chart Position': '1', 'Label': 'Parlophone(UK)', 'Released': '22 March 1963', 'US Chart Position': '-', 'RIAA Certification': 'Platinum', 'BPI Certification': 'Gold'}
    tenthline = {'Title': '', 'UK Chart Position': '1', 'Label': 'Parlophone(UK)', 'Released': '10 July 1964', 'US Chart Position': '-', 'RIAA Certification': '', 'BPI Certification': 'Gold'}

    #assert d[0] == firstline
    #assert d[9] == tenthline
    print d[0]
    print firstline
    #print d[9]

test()

我得到的结果是:

{'Title': 'Please Please Me', 'UK Chart Position': '1', 'Label':    'Parlophone(UK)', 'Released': '22 March 1963', 'US Chart Position': '\xe2\x80\x94', 'RIAA Certification': 'Platinum', 'BPI Certification': 'Gold'}
{'Title': 'Please Please Me', 'UK Chart Position': '1', 'Label': 'Parlophone(UK)', 'Released': '22 March 1963', 'US Chart Position': '-', 'RIAA Certification': 'Platinum', 'BPI Certification': 'Gold'}

1 个答案:

答案 0 :(得分:1)

该字符是 em-dash ,而不是连字符

它工作正常。

只有困扰你的是字典的代表

>>> print '\xe2\x80\x94'
—
>>> print {1: '\xe2\x80\x94'}
{1: '\xe2\x80\x94'}

要正确打印dict,请执行此恐怖

>>> d = {1: '\xe2\x80\x94'}
>>> print repr(d).decode("unicode-escape").encode("latin-1")
{1: '—'}