43 — Text stats: letters, words, and the longest one
What comes out of a file is one piece of text. There are usually three things you want from it — how long it is, how many words, and which word is the longest.
A program that writes files does not run on the site.
Steps
Save it and read it back, exactly as in guide 37:
run it →set text to the weather is very good today write text to "memo.txt" read "memo.txt" into memo show memoLetters and words are two sentences:
run it →set memo to the weather is very good today show the length of memo set words to memo split by space show how many words30and6.The longest word is found by comparing one at a time. Keep the best so far in a name and replace it when something longer turns up:
run it →set words to list of the, weather, is, good set longest to the first of words set best to the length of longest for each word in words set size to the length of word if size is greater than best set longest to word set best to size end end show longestYou get
weather. The lengths go into names first — a reading cannot be written straight into the right-hand side of a comparison.The whole thing:
run it →set text to the weather is very good today write text to "memo.txt" read "memo.txt" into memo show the length of memo set words to memo split by space show how many words set longest to the first of words set best to the length of longest for each word in words set size to the length of word if size is greater than best set longest to word set best to size end end show longest show best
Try it yourself
Find the shortest word too — change is greater than to is less than.
Then count the lines: set lines to memo split by line, then
show how many lines.
What you learned
- What comes out of a file is one piece of text; splitting it makes a list.
the length ofis letters;how manyon the split list is words.- The longest is found by keeping the best so far and comparing one at a time.
- A reading goes into a name before it can be compared against.