您好,我有一个文本文件
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
循环中,您将在成功找到句子中的特定字符串时编写字符串。您只需要在检查完所有单词后才将字符串写到文本上-这就是为什么文本文件中会重复某些句子的原因。这是因为句子中有多个匹配字符串。
因此,请执行以下操作:
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将会为您感到骄傲:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句