【问题标题】:Matlab: Find string pattern with a list of words and replace in text with one word of the listMatlab:用单词列表查找字符串模式并用列表中的一个单词替换文本
【发布时间】:2021-05-22 22:35:47
【问题描述】:

在 Matlab 中,考虑字符串:

str = 'text text text [[word1,word2,word3]] text text'

我想随机分离列表中的一个单词('word1','word2','word3'),说'word2',然后在可能的新文件中写入字符串:

strnew = 'text text text word2 text text'

我的做法如下(肯定很糟糕):

隔离字符串'[[word1,word2,word3]]'可以通过

str2=regexp(str,'\[\[(.*?)\]\]','match')

去掉字符串中的开闭方括号是通过

实现的
str3=str2(3:end-2)

最后我们可以将 str3 拆分成一个单词列表(存储在一个单元格中)

ListOfWords = split(str3,',')

输出{'word1'}{'word2'}{'word3'},我被困在那里。如何选择其中一个条目并将其重新插入初始字符串(或它的副本......)?请注意,分隔符 [[]] 都可以更改为 ||,如果有帮助的话。

【问题讨论】:

  • 想要的单词是程序随机选择的,还是程序知道要选择哪个单词?
  • @Luis Mendo 程序随机选择。
  • 您的示例中的text 保证不包含[[]],对吗?请在问题描述中澄清这一点
  • @Luis Mendo 对这个问题和请求都是肯定的。

标签: string matlab find


【解决方案1】:

我有一个可怕的解决方案。我试图看看我是否可以在一个函数调用中做到这一点。你可以……但代价是什么!像这样滥用动态正则表达式几乎不能算作一次函数调用。

我使用动态表达式来处理逗号分隔的列表。棘手的部分是选择一个随机元素。这变得非常困难,因为 MATLAB 的语法不支持对函数调用的结果进行括号索引。为了解决这个问题,我把它放在一个结构中,这样我就可以点索引。这太可怕了。

>> regexprep(str,'\[\[(.*)\]\]',"${struct('tmp',split(string($1),',')).tmp(randi(count($1,',')+1))}")

ans =

    'text text text word3 text text'

Luis 肯定有最好的答案,但我认为不使用正则表达式可以稍微简化一下。

str = 'text text text [[word1,word2,word3]] text text';                     % input
tmp = extractBetween(str,"[[","]]");                                        % step 1
tmp = split(tmp, ',');                                                      % step 2
chosen_word = tmp(randi(numel(tmp))) ;                                      % step 3
strnew = replaceBetween(str,"[[","]]",chosen_word,"Boundaries","Inclusive") % step 4

【讨论】:

    【解决方案2】:

    你可以这样做:

    1. regexp'split' 选项一起使用;
    2. 将中间部分拆分成单词;
    3. 随机选择一个词;
    4. 向后串联。

    str = 'text text text [[word1,word2,word3]] text text';     % input
    str_split = regexp(str, '\[\[|\]\]', 'split');              % step 1
    list_of_words = split(str_split{2}, ',');                   % step 2
    chosen_word = list_of_words{randi(numel(list_of_words))};   % step 3
    strnew = [str_split{1} chosen_word str_split{3}];           % step 4
    

    【讨论】:

      猜你喜欢
      • 2014-02-20
      • 1970-01-01
      • 2013-03-17
      • 2016-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      • 2018-06-02
      相关资源
      最近更新 更多