[英]convert to ascii or string in Python 2.7
I'm reading and parsing a csv file into a dictionary. 我正在读取csv文件并将其解析为字典。 However, one of the values is this '\\xe2\\x80\\x94'
instead of this '-'
. 但是,值之一是此'\\xe2\\x80\\x94'
而不是此'-'
。 How can I convert the value to its proper format? 如何将值转换为正确的格式? type('\\xe2\\x80\\x94')
says it's a string because of the quotes but in the file it's a hyphen character. 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()
Results I get are: 我得到的结果是:
{'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'}
And it is working correctly. 而且它工作正常。
Only thing that is troubling you is representation of dictionaries 唯一困扰您的是字典的表示形式
>>> print '\xe2\x80\x94'
—
>>> print {1: '\xe2\x80\x94'}
{1: '\xe2\x80\x94'}
To print the dict properly do this horror 要正确打印字典,请执行此操作
>>> d = {1: '\xe2\x80\x94'}
>>> print repr(d).decode("unicode-escape").encode("latin-1")
{1: '—'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.