繁体   English   中英

在python 2.7中转换为ascii或字符串

[英]convert to ascii or string in Python 2.7

我正在读取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'}

字符是破折号 ,而不是连字符

而且它工作正常。

唯一困扰您的是字典的表示形式

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

要正确打印字典,请执行此操作

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM