在Windows7编码下发布python3.4 - \ u2014

时间:2016-01-28 13:29:01

标签: encoding python-3.4

我的python代码中有'em dash'字符,用它在某个txt文件中分割一行。

with open(path, 'r') as r:
    number = r.readline()
    num = number.split(' — ')[1].replace('\n',' — ')

使用python3.4在ubuntu下运行正常,但是在Windows 7(python3.4)下运行代码时会出现以下错误。

  

num = number.split('\ u2014')[1] .replace('\ n','\ u2014')IndexError:   列表索引超出范围

我确信它应该可行,似乎问题出在编码上。 将不胜感激任何修复我的程序的帮助。我试图设置“# - - coding:utf-8 - - ”而没有任何结果

解决方案是open(path, mode, encoding='UTF8')

1 个答案:

答案 0 :(得分:0)

当你这样做时:

num = number.split(' — ')[1].replace('\n',' — ')

你假设字符串'数字'包含一个破折号,然后取第二个字段([1]),如果数字不包含破折号,则[1]不存在,只有[0]存在,并且索引超出范围响应。

if ' — ' in number: 
   num = number.split(' — ')[1].replace('\n',' — ')
else:
   num = number.replace('\n',' — ')

此外,正如您现在在Windows上一样,您可能想要检查' \ r \ n'以及' \ n'取决于文件使用什么作为行尾字符