【问题标题】:convert to ascii or string in Python 2.7在 Python 2.7 中转换为 ascii 或字符串
【发布时间】:2016-05-27 08:19:12
【问题描述】:

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

【问题讨论】:

  • 那个地方好像有一些看不见的字符

标签: python python-2.7 csv encoding


【解决方案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: '—'}

【讨论】:

  • 对于这样的字典 d = {'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'} 我应该像 d['US图表位置'] = d['美国图表位置'].decode("unicode-escape").encode("latin-1")?
  • 不,如果你不打印整个dict,print d['US Chart Position']就足够了
猜你喜欢
  • 2018-03-07
  • 2017-03-30
  • 2012-01-17
  • 1970-01-01
  • 2016-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-26
相关资源
最近更新 更多