Generating a Dictionary Function
이전 댓글 표시
Hi All,
How would i make a function called 'Word' that determines whether the user has input a real english word, determined based on the content within a file called 'dictionary.txt', which contains the whole english dictionary.
For example, a worked example from the users perspective would be as follows:
What is the word? 'kinbecef'
Not a word. Try Again.
What is the word? 'Community'
... (continue on with code)
Kind Regards,
Smoxk x
댓글 수: 7
DGM
2022년 4월 26일
Should I assume that I'm also supposed to write the dictionary as well? If it exists, is the format defined or known?
Smoxk x
2022년 4월 26일
Smoxk x
2022년 4월 26일
Jan
2022년 4월 26일
This sounds like a homework question. So please show, what you have tried so far.
How is the dictionary stored? One word per line? Separated by spaces? A MAT file? If it is a text file, fileread and strsplit can create a cell string containing the words. If you sort it, ismember might be a fast way to find a word in the list. Do you care about the upper/lower case? strcmp is an option also.
Smoxk x
2022년 4월 26일
Walter Roberson
2022년 4월 26일
while ~strcmpi(Inputword, import)
%get a new word
end
Jan
2022년 4월 26일
@Smoxk x: Your code has several problems.
- Do not use "size" as a name of a variable, because it is an important Matlab function. This can cuase unexpected behavior, if you try to use the function later.
- "Num" is not defined.
- "InputWord" is uded, before it is defined.
- "file(i)" is the i.th character of the file name.
- ~= compares char vectors elementwise, so both must have the same length or one can be a scalar.
채택된 답변
추가 답변 (2개)
Jan
2022년 4월 26일
function Word
Data = fileread('YourDictionary.txt');
List = sort(lower(strsplit(Data, char(10))));
while 1
s = input('Input a word: ', 's');
% insert the checks and the oputput here...
% Stop the loop with "break;" if s is empty
end
end
You can use container.Map. I give here example of numbers, but it can handle char array or strings as well.
The time access, using hash is O(1) and is much quicker than ismember (and this test on TMW server seems to invalid Walter's claim that ismember on sorted array is faster, perhaps because MATLAB ismember doesn't know/check array is sorted, and it sorts anyway and we all know some sorting algorithms are not fast when working on already sorted input):
a=randi(1e6,1,1e6);
as=sort(a);
m=containers.Map(a,a);
b=randi(1e6,1,1e3);
tic; for k=1:numel(b); ismember(b(k),as); end; toc
tic; for k=1:numel(b); ismember(b(k),a); end; toc
tic; for k=1:numel(b); isKey(m,b(k)); end; toc
카테고리
도움말 센터 및 File Exchange에서 Dictionaries에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!