是否有更可靠的替代品替代mimetypes.guess_extension()? [英] Is there a more reliable drop-in replacement for mimetypes.guess_extension()?

查看:456
本文介绍了是否有更可靠的替代品替代mimetypes.guess_extension()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我反对以下内容(Ubuntu Trusty上的Python 2.7.10):

I'm up against the following (Python 2.7.10 on Ubuntu Trusty):

>>> from mimetypes import guess_extension
>>> guess_extension('text/html')
'.html'
>>> guess_extension('application/json')
'.json'
>>> guess_extension('text/plain')
'.ksh'
>>> guess_extension('audio/mp3')
>>>

它正确地处理了text/html和application/json,对text/plain做出了错误的猜测,而对于audio/mp3却一无所获. (有趣的是,将最后一个更改为音频/mpeg将按预期返回'.mp3',但这不是我的数据源使用的.)

It got text/html and application/json right, made a bad guess for text/plain, and gave me nothing for audio/mp3. (Interestingly, changing the last one to audio/mpeg returns '.mp3' as expected, but that's not what my data source uses.)

此模块是否有更可靠的替代方案,在最近两种情况下会返回'.txt''.mp3'?我研究了python-magic,但是根据我所看到的一切,看来它需要读取实际的文件数据才能起作用.就我而言,我所拥有的只是MIME类型作为字符串.

Is there a more reliable alternative to this module that would return '.txt' and '.mp3' in my last two cases? I looked into python-magic, but based on everything I saw it looks like it needs to read the actual file data to function. In my case, all I have is the MIME type as a string.

推荐答案

如果要处理的修正集是guess_extension出现错误的mimetypes,请在猜测之前放一个替代字典.

If you're dealing with a fix set of mimetypes that guess_extension is getting wrong, put an override dictionary ahead of the guess.

known_extension = {'text/html': '.txt', ...}
...
extension = known_extension.get(mimetype) or guess_extension(mimetype)

这篇关于是否有更可靠的替代品替代mimetypes.guess_extension()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆