How to find all the words contains certain letter from a text file?
5 views (last 30 days)
Show older comments
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 Comment
Stephen23
on 31 Aug 2017
Read about regular expressions:
To practice using regular expressions download my FEX tool:
Answers (1)
OCDER
on 31 Aug 2017
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
0 Comments
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!