【问题标题】:Text formating - write out words following XY文本格式 - 写出 XY 之后的单词
【发布时间】:2013-11-09 11:47:36
【问题描述】:

我是 MATLAB 的新手,我的家庭作业中有一段文本,我需要从中选择“and”或“And”之后的单词,然后将每个字母 X 替换为字母 Y。我知道该怎么做在 python 中通过 .split() 并循环通过我搜索 X 的 sting(word)。但是,在 matlab 中我迷路了。你能告诉我是否有一些等效的命令吗?类似命令的东西

    fileread
    textscan
    fseek

谢谢

编辑:

我的实际意思是来自一个字符串:

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

我需要获取

    'pineapples'
    'other'

并返回这些 'e' 切换为 'z'

【问题讨论】:

    标签: matlab


    【解决方案1】:

    使用普通的case-insensitive regular expressions。查找andAnd 之后的所有内容,并将XY 切换:

    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'
    

    【讨论】:

    • 谢谢,但我意识到我不够具体。我需要按照你的描述找到X,例如从str ='我喜欢胡萝卜和菠萝等水果'我需要获得'菠萝'和'其他',然后在这些中,我需要将'e'更改为' z',只返回修改后的单词,不返回原来的语句。
    • @matlab-oh-no:查看更新后的答案。它有点长,但又一次:我认为它有效 =)
    • 你好,不幸的是,这段代码似乎写出了所有包含字母'e'的单词,无论它们是否跟随'AND'(我将整个文本设为大写),列表从文本中第一个“AND”之后找到的第一个单词开始选择的单词。根据我的理解,你的意思是 'str2' 只包含 'AND' 之后的单词?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多