如何在matlab中用条件提取文本中的单词?

时间:2017-03-01 13:39:10

标签: matlab nlp preprocessor

我有多个文本文件,只想提取一个带条件的值

文件看起来像这样

157.76941498460488, u'id': 1056080, u'image_id': 354282, u'bbox':      [188.68243243243242, 229.17468354430378, 16.21621621621621, 9.729113924050637], u'legibility': u'illegible', u'class': u'machine printed'}, {u'language': u'na', u'area': 157.76941498460522, u'id': 1056081, u'image_id': 354282, u'bbox': [176.79054054054052, 241.06582278481014, 16.216216216216246, 9.729113924050637], u'legibility': u'illegible', u'class': u'machine printed'}, {u'language': u'na', u'area': 130.89018132056108, u'id': 1056082, u'image_id': 354282, u'bbox': [60.03378378378378, 224.8506329113924, 15.13513513513514, 8.648101265822783], u'legibility': u'illegible', u'class': u'machine printed'}, {u'language': u'english', u'area': 229.08553456429397, u'class': u'machine printed', u'utf8_string': u'7206', u'image_id': 354282, u'bbox': [447.84940154212785, 338.8799273943157, 15.489338584815993, 14.78988488177692], u'legibility': u'legible', u'id': 1232932}, {u'language': u'english', u'area': 125.41629858832702, u'class': u'machine printed', u'utf8_string': u'HSS', u'image_id': 354282, u'bbox': [465.63345695432395, 333.1362827800334, 10.039386119788142, 12.492427036063997], u'legibility': u'legible', u'id': 1232933}]  

我想提取所有bbox,如果它的utf8_string,以及输出存储,就像这样

bbox = [188.68243243243242, 229.17468354430378, 16.21621621621621, 9.729113924050637]
bbox1 = [60.03378378378378, 224.8506329113924, 15.13513513513514, 8.648101265822783]
..etc bbox3 and box4 all the bboxs if its 'utf8_string'and legible

我的代码

i=imread('image.JPEG');

fid = fopen('text1.txt','r');
C = textscan(fid, '%s','Delimiter','');
fclose(fid);
C = C{:};

box = ~cellfun(@isempty, strfind(C,'bbox'));

output = [C{find(box)}]

我不仅仅是bbox的全线。

1 个答案:

答案 0 :(得分:0)

这是使用正则表达式进行此提取的代码示例。它可能不是世界上最快的,也不是最强大的,但如果你的文本文件很小,它就能完成这项工作。它可以让您了解如何在这种情况下继续操作,并修改代码,以便在必要时可以完全使用您的数据。

我想您在[filepathList]

中有一个文件列表
Cdata = cell(numel(filepathList),1);
for i=1:numel(filepathList)
    fid = fopen(filepathList{i});
    tline = fgetl(fid);

    % find the bbox blocks
    C = regexp(tline,'u''bbox'': +\[([0-9\. ,]+)\]','tokens');
    C = cellfun(@(x) x{1},C,'UniformOutput',false)';

    % in each block, find the numbers
    C2 = cellfun(@(x) textscan(x,'%f','Whitespace',', '),C,'UniformOutput',false);
    Cdata{i} = cell2mat(cellfun(@(x) x', cat(1,C2{:}),'UniformOutput',false));
    fclose(fid);
end

希望这有帮助!

相关问题