How to find all the words contains certain letter from a text file?
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
Stephen23
am 31 Aug. 2017
Read about regular expressions:
To practice using regular expressions download my FEX tool:
Antworten (1)
OCDER
am 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 Kommentare
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!