python / nautilus脚本组合的奇怪的字符编码问题

时间:2012-12-07 09:04:16

标签: python unicode encoding

我有一个nautilus脚本将我喜欢的音乐复制到一个特殊的文件夹中,我同步到我的手机和我的车。它在路径上失败了,其中有一些有趣的角色。我正在逐步修复它,比如:

temp = temp.replace('%20', ' ')
temp = temp.replace('%5B', '[')
temp = temp.replace('%5D', ']')

但是我已经厌倦了这些绑定解决方案,我确信有更好的方法可以使用str.encodestr.decode执行此操作。

有没有人认识到这种奇怪的编码以及我如何正确处理它?问题是,例如,我有一个文件夹,如

/media/music/kálmán balogh and the gipsy cimbalom band/aven shavale

在我的磁盘上,但当我使用os.getenv('NAUTILUS_SCRIPT_CURRENT_URI'),即nautilus中当前选择的文件夹,它出现在python中

/media/music/k%C3%A1lm%C3%A1n balogh and the gipsy cimbalom band/aven shavale

然后重命名或复制文件等其他操作不起作用,因为它在磁盘上找不到该文件。

1 个答案:

答案 0 :(得分:2)

您正在查看网址编码。使用urllib.unquote()将这些解释为UTF-8编码文本,然后解码为unicode:

>>> import urllib
>>> urllib.unquote('/media/music/k%C3%A1lm%C3%A1n balogh and the gipsy cimbalom band/aven shavale').decode('utf8')
u'/media/music/k\xe1lm\xe1n balogh and the gipsy cimbalom band/aven shavale'
>>> print urllib.unquote('/media/music/k%C3%A1lm%C3%A1n balogh and the gipsy cimbalom band/aven shavale').decode('utf8')
/media/music/kálmán balogh and the gipsy cimbalom band/aven shavale

在Python 3中,您需要使用urllib.parse.unquote();功能被移动了。

相关问题