文本格式 - 在XY后面写出单词

时间:2013-11-09 11:47:37

标签: matlab

我对MATLAB相当新,我的作业中有一段文字,我需要在“和”或“和”之后选择单词,然后将每个字母X替换为字母Y.我知道如何做到这一点在python中通过.split()并循环通过sting(word)我搜索X.但是,在matlab中我迷失了。你能否告诉我是否有一些等效命令?像

这样的命令
    fileread
    textscan
    fseek

谢谢

编辑:

我的行为意味着来自一个字符串:

    str = 'I like apples and pineapples and other fruit'

我需要获得

    'pineapples'
    'other'

并将'e'切换为'z'

返回

1 个答案:

答案 0 :(得分:0)

使用常规case-insensitive regular expressions。查找andAnd后的所有内容,并使用X切换Y

str = 'This is a text with X and X and Z'
[startIndex,endIndex] = regexpi(str,'and');
str2 = str(endIndex(1) + 1 : end)
str2(str2 == 'X') = 'Y';
str = [str(1:endIndex), str2]

str =

This is a text with X and Y and Z

有点乱。我想它可以做得更简单,但至少它可以工作!如果您不了解X的情况,请使用strcmpi代替==

更新#:

发表评论后,我想这应该有效:

[startIndex,endIndex] = regexpi(str,'and');
str2 = str(endIndex(1) + 1 : end);
words = regexp(str2,' ','split');
nums = cellfun(@(x) find(x == 'e'), words, 'UniformOutput', false);
[idx] = find(~cellfun(@isempty, nums));
wordList = words(idx)
wordList(wordList == 'e') = 'X'