如何用“*”替换文本文件中的某些单词?

How do I replace certain words in a text file with '*'?

你好,我有一个文本文件

  Treadstone project

  Jason Bourne is to neutralize Wombosi.

  Nicky Parsons is the technician on the job

  Bourne has shown interest in Marie Kreutz

  Do not leak information about Blackbriar.

我有一个元胞数组

words = {'treadstone','bourne','wombosi','parsons','blackbriar'}

我想得到这个

********** project

Jason ****** is to neutralize *******.

Nicky ******* is the technician on the job

****** has shown interest in Marie Kreutz

Do not leak information about **********.

但是我的代码正在打印这个

********** project

Jason ****** is to neutralize Wombosi

Jason bourne is to neutralize *******.

Nicky ******* is the technician on the job

****** has shown interest in Marie Kreutz

Do not leak information about **********.

这是我的代码:

while ischar(line)
if strcmp(line, '')
    fprintf(output, line);
    line = fgetl(fh);
end
[T N] = size(words);
for i = 1:N
    mat = words{i}; %extreact the first word to comapre it to the text file
    if strfind(lower(line), mat)
        t = mat; 
        t(1:end) = '*'; %replace the word with *
        ht = strfind(lower(line), mat); %find its location 
        hat = lower(line(ht));
        line(ht) = hat; %replace the word with lower case
        lalu = strrep(line, mat, t); 

        fprintf(output, '%s\n', lalu);
    else 
        hat = 0;
    end


end

line = fgetl(fh);
end

如有任何帮助,我们将不胜感激。谢谢。

您的代码大部分都有效。但是,如果一个句子中有多个匹配字符串,则说明您没有正确更新该句子以屏蔽每个单词。您只是单独阻止单词,而不是更新一个字符串中的所有单词。完成后,您还需要将 fprintf 语句放在内部循环之外。通过将 fprintf 语句放在 for 循环中,您可以在句子中成功找到特定字符串时写入字符串。您只想在检查 all 个单词后将字符串写入文本 - 这就是为什么您的文本文件重复某些句子的原因。这是因为你在句子中有多个匹配字符串。

因此,做这样的事情:

while ischar(line)
if strcmp(line, '')
    fprintf(output, line);
    line = fgetl(fh);
end
[T N] = size(words);
for i = 1:N
    mat = lower(words{i}); %extreact the first word to comapre it to the text file
                           % Also cast to lower to ensure case-sensitive
    if strfind(lower(line), mat)
        t = mat; 
        t(1:end) = '*'; %replace the word with *
        ht = strfind(lower(line), mat); %find its location 
        hat = lower(line(ht));
        line(ht) = hat; %replace the word with lower case
        line = strrep(line, mat, t);   %// UPDATE STRING HERE
    else 
        hat = 0;
    end           
end

fprintf(output, '%s\n', line); %// Print out string once all replacing is done

line = fgetl(fh);
end

在让您的代码运行之前,我必须进行一些设置。我将您的文本放在一个名为 bourne.txt 的文件中,然后在 运行 代码之前执行此操作:

fh = fopen('bourne.txt', 'r');
line = fgetl(fh);
words = {'treadstone','bourne','wombosi','parsons','blackbriar'};
output = fopen('output.txt', 'w');

我把文字写给了output.txt。当我使用上面的代码和 运行 更正后的代码时,我得到:

 ********** project
 Jason ****** is to neutralize *******.
 Nicky ******* is the technician on the job
 ****** has shown interest in Marie Kreutz
 Do not leak information about **********.

既然我们已经成功地对您的文本文件进行了分类,Jason Bourne 会感到自豪: