我要做的是创建一个Modula-2程序,该程序接收一个文件并返回读取文件中的多个单词以及每个单词的读取频率。就好像一个文件说:“狐狸狐狸跳过懒狗。”输出将是
MODULE FindWords;
FROM StreamFile IMPORT ChanId, Open, read, Close, OpenResults;
FROM TextIO IMPORT ReadString, WriteLn, WriteString, WriteChar, SkipLine;
FROM IOResult IMPORT ReadResult, ReadResults;
FROM StdChans IMPORT StdInChan, StdOutChan;
FROM WholeIO IMPORT WriteInt, WriteCard;
TYPE line = ARRAY[0..120] OF CHAR;
AllLines = ARRAY [1..1000] OF line;
word = ARRAY[0..20] OF CHAR;
WordFreq = RECORD
freq : INTEGER;
aword : word;
END;
AllWords = ARRAY [1..1000] OF WordFreq;
VAR
infile, stdOut, stdIn : ChanId;
res : OpenResults;
inputline: line;
i, j, k : INTEGER;
x, y, z : INTEGER;
charval : INTEGER;
numlines: INTEGER;
wordindex: INTEGER;
numwords: INTEGER;
document: AllLines;
wordsindoc: AllWords;
freqindoc: AllWords;
BEGIN
y:=0;
stdOut := StdOutChan();
stdIn := StdInChan();
Open (infile, "input.txt", read, res);
IF res = opened
THEN
i := 1;
REPEAT
ReadString (infile, inputline);
WriteString (stdOut, inputline);
IF ReadResult (infile) = allRight
THEN
SkipLine (infile);
document[i]:=inputline;
WriteLn (stdOut);
i:=i+1;
END; (* if *)
UNTIL ReadResult (infile) # allRight;
Close (infile);
WriteLn (stdOut);
ELSE
WriteString (stdOut,"Sorry, couldn't open the file");
WriteLn (stdOut);
END; (* if *)
numlines :=i-1;
(* in order to identify words in each line*)
numwords:=0;
wordindex := 1;
FOR i:=1 TO numlines DO
j:=0; k:=0;
WHILE ORD(document[i][j]) <> 0
DO
charval := ORD(document[i][j]);
IF ((charval >= 48) AND (charval < 58)) OR
((charval >= 65) AND (charval < 91)) OR
((charval >= 97) AND (charval < 123)) OR
((charval = 45)) OR ((charval=39))
THEN
wordsindoc[wordindex].aword[k] := document[i][j];
WriteChar(stdOut, wordsindoc[wordindex].aword[k]);
k:=k+1;
ELSE
WriteLn (stdOut);
wordindex:=wordindex+1;
numwords:=numwords+1;
k:=0;
END;
j:=j+1;
END;
END;
numwords:=numwords-1;
WriteInt(stdOut, numwords, 3);
WriteLn(stdOut);
END FindWords.
(9这里是单词的总数。)到目前为止,我已经得到了总字数计数器,并且所有单词都以这种方式显示,但我仍然坚持如何实现频率每个字的反击。这是代码。
{{1}}