How to find all the words contains certain letter from a text file?
조회 수: 5 (최근 30일)
이전 댓글 표시
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
Stephen23
2017년 8월 31일
Read about regular expressions:
To practice using regular expressions download my FEX tool:
답변 (1개)
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!