如果数据的格式略有损坏,是否仍然可以确定其文件类型

If the format of a data is slightly broken, is it still possible to determine its filetype?

本文关键字:类型 文件 是否 格式 数据 损坏 如果      更新时间:2023-09-26

我有一个随机的文本数据,我需要确定它的文件类型,例如.xls,.csv,.tsv,.json和.html。目前,我正在使用蛮力针对所有不同的格式解析文件。

当文件略有损坏时,会出现我的问题,并且在解析过程中会失败。在这些情况下,是否有一个相当好的启发式方法可以猜测文件类型,以便我可以根据这种格式进一步"lint"数据?

我正在使用node.js,以防已经有一个库。我对node.js之外的解决方案持开放态度。

我尝试使用 mmmagic,但它只返回"text/plain",而不是我需要的信息(.tsv、.json、.xml),livescript 中的示例代码:

useMagic = (res)->
    buf = new Buffer res.body
    magic = new mmmagic.Magic! ##return UTF-8 Unicode text, with very long lines, with no line terminators
    #magic = new mmmagic.Magic mmmagic.MAGIC_MIME ## return text/plain; charset=utf-8
    #magic = new mmmagic.Magic mmmagic.MAGIC_MIME_TYPE ##text/plain

    err, magicalres <- magic.detect buf
    magicalres |> console.log 

url = "https://sheethub.com/data.fda.gov.tw/%E4%B8%8D%E7%AC%A6%E5%90%88%E9%A3%9F%E5%93%81%E8%B3%87%E8%A8%8A%E8%B3%87%E6%96%99%E9%9B%86/i/96/%E7%B3%AF%E7%B1%B3?page=1&format=json"
err, res, body <- request {"url": url, "encoding": null}
result = res |> useMagic

我正在添加编译的javascript代码,也许这会更容易:

request = require('request');
mmmagic = require('mmmagic');

useMagic = function(res){
  var buf, magic;
  buf = new Buffer(res.body);
  magic = new mmmagic.Magic();
  return magic.detect(buf, function(err, magicalres){
    return console.log(
    magicalres);
  });
};
url = "https://sheethub.com/data.fda.gov.tw/%E4%B8%8D%E7%AC%A6%E5%90%88%E9%A3%9F%E5%93%81%E8%B3%87%E8%A8%8A%E8%B3%87%E6%96%99%E9%9B%86/i/96/%E7%B3%AF%E7%B1%B3?page=1&format=json";
request({
  "url": url,
  "encoding": null
}, function(err, res, body){
  var result;
  return result = useMagic(
  res);
});

我一直在使用包括res.headers['content-type']在内的方法组合,但仍然存在所有方法都失败的情况。

你厌倦了提供与libmagic绑定的mmmagic模块吗?

它允许检查文件中已知的"魔术"标识符。通常,它只需要访问文件的前几个字节即可执行此操作。

我想这种方法本身可能被认为是"蛮力",但至少它依赖于一个众所周知且经过良好测试的库。

在最初建议mmmagic未能提供魔法后更新:

如果您始终使用请求模块通过 HTTP(S) 请求数据,则响应标头可能会提供提示:

// returns 'text/json' for your data.fda.gov.tw sample
var mimeType = res.headers['content-type'];

如果做不到这一点,fsql Perl 模块包含基于正则表达式的逻辑,用于确定文本是否是 CSV、TSV、YAML 或 JSON,这些文本可能适合在您自己的代码中重新调整用途。