How to find all the words contains certain letter from a text file?

조회 수: 5 (최근 30일)
hello
hello 2017년 8월 31일
답변: OCDER 2017년 8월 31일
Suppose I have a text file and I want to find all the words that contain letter d(just lowercase). How do I implement this in Matlab?

답변 (1개)

OCDER
OCDER 2017년 8월 31일
Try the following code for opening a file and looking for a word with lower case d.
FID = fopen('filename.txt', 'r'); %Open a file to read
Pattern = '\w*d+\w*'; %regexp search pattern for a word with lower case d
% \w* any alphabet letter (\w), 0 or more (*)
% d+ any lowercase d (d), 1 or more (+)
WordList = {}; %Stores all the words with d in it
WordLine = []; %Stores all the line number for each word that has d in it
Line = 1; %Line number to read
while feof(FID) == 0 %Check if the end of file has not been reached
GetText = fgetl(FID); %Read the next line of the file
FoundWord = regexp(GetText, Pattern, 'match'); %Search for all words that match the Pattern in the GetText string
if ~isempty(FoundWord)
WordList = [WordList; FoundWord']; %Add the found word to the list
WordLine = [WordLine; Line*ones(length(FoundWord), 1)]; %Save the line number where the word was found
end
Line = Line +1;
end
fclose(FID); %Close the file that was read to free up memory
[num2cell(WordLine) WordList] %Show the output in matlab

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by