【问题标题】:How can I search a text file for specific words using matlab?如何使用 matlab 在文本文件中搜索特定单词?
【发布时间】:2014-03-10 15:39:12
【问题描述】:

我需要在 matlab 中编写一个程序,在文本文件中搜索关键词,然后读入这些词之后的内容,然后继续搜索。我尝试使用 fscanf 或 textscan,但我一定遗漏了一些东西

我有一个文本文件,内容如下:

Maria, female,24,married
       born in USA

George, male,32,married
        born in Germany    

名字乔治之前有一个空行。 例如,我想阅读 Maria,然后阅读 Maria 之后的内容,直到空行。

【问题讨论】:

  • 你可能不想听到这个,但 Matlab 并不是文本处理的正确工具。我会推荐第一个 perl(因为我已经习惯了),但是由于很多人不喜欢它,我会说 python 也是一个不错的选择,而且比 Matlab 更好。
  • 这个问题对我来说不是很清楚......你在期待什么?您是否期待一种不同的方法来提高搜索或阅读的速度?或者您是否期望一种方法来解析 texscan 的输出?
  • 另外,当您说 我尝试使用 fscanf 或 textscan 但我一定遗漏了一些东西时,请see this 否则我们无法帮助您。
  • 使用 textscan 将文件读入行的元胞数组。然后使用 strcmp 和 length 来识别以 Maria 开头的行和空白行,您可以使用这些索引来提取所需的行。使用 textscan 发布您的代码将有助于确定它为什么不起作用。

标签: matlab text-processing text-parsing textscan


【解决方案1】:

您可以使用textscan 读取整个文件,搜索关键字,提取找到的行,然后将这一行与下一行连接起来。

这里是一个例子,寻找Maria

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

Lia = ~cellfun(@isempty, strfind(C,'Maria'));

output = [C{find(Lia)} ',' C{find(Lia)+1}]

给了

Maria, female,24,married,born in USA

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-30
    • 2022-12-06
    • 2015-01-31
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多