% File I/O - Reading and Writing Text Files

Total Page:16

File Type:pdf, Size:1020Kb

% File I/O - Reading and Writing Text Files

% Agenda % % File I/O - reading and writing text files % % Steps: % - open the file with fopen(name, why) % - iterate: % reading a line until the end of the file % - close the file % % Structures and Structure Arrays % % 3 ways to make a structure: % One field at a time % the dreaded struct(...) function % custom function open file fopen() fclose() fgets(fh) %reads whole line with \n fget1(fh) % reads line without last character ischar(ln) % used with in a line, usually Spreadsheets : [nums txt raw] xlsread( 'grades.xls')

****** Tokenizing Update from last class ******

***** Input Script ******************** clear clc reading_level('declaration.txt') reading_level('mercy.txt') reading_level('gettysburg.txt') % reading_level('green_eggs_and_ham.txt')

******* Tokenizing Function ******* function reading_level(name) global words % global variables in function global sentences global syllables % reading_level = 0.39 * total_words/total_sentences ... % + 11.8 * total_syllables / total_words ... % -15.59 words = 0; % initialize variables sentences = 0; syllables = 0; % open the file fid = fopen(name, 'r'); % opens file to read r-read, w-write, a-append line = ''; % initialize line variable while ischar(line) line = fgetl(fid); % gets line to process if ischar(line) % process line, calls function process(line) end end % Calculate reading level level = 0.39 * words/sentences ... + 11.8 * syllables / words ... -15.59; out = fopen('reading_data.txt', 'a'); % appends to file, not over fprintf(out, 'There were %d words, %d sentences, %d syllables\n', ... words, sentences, syllables); % prints to file handle 'out' fprintf(out, 'reading level for %s is %2.2f\n', name, level); fclose(out); end

%******** Process Line Function ********** function process(line) % hummm no output global words % globals for use in another function global sentences global syllables % fprintf('%s\n', line) if length(line) > 0 && line(1) ~= '%' % don't do comments while length(line) > 0 %while line do [word line] = strtok(line,' .,-;:?!'); % tokenize if length(word) > 0 words = words + 1; % adds a word sylls = ceil(length(word)/3); % not real way, but ok syllables = syllables + sylls; %adds syllables end if length(line) > 0 ch = line(1); %checks to see if sentence if ch == '.' || ch == '!' || ch == '?' sentences = sentences + 1; end %if ch end % if line end % while line end %if line end % function

***** Output File **** reading_data.txt ******

There were 1323 words, 36 sentences, 2585 syllables reading level for declaration.txt is 21.80 There were 103 words, 1 sentences, 185 syllables reading level for mercy.txt is 45.77 There were 272 words, 10 sentences, 470 syllables reading level for gettysburg.txt is 15.41 There were 812 words, 137 sentences, 1113 syllables reading level for green_eggs_and_ham is 2.90

______Another IO Example ______functions Frednew and Lookup

______function fred clc

in = fopen('mercy.txt','r'); out = fopen('newMercy.txt', 'w'); line = ' '; delim = ' ,;:.'; while ischar(line) line = fgetl(in); if ischar(line) % fprintf('%s\n', line); while length(line) > 0 [word line] = strtok(line, delim); word = lookup(word); fprintf(out, '%s ', word); end fprintf(out, '\n'); end end end

______function word = lookup(word) dict = {'strain''''''d', 'under pressure'; 'blesseth','makes ''appy'; 'droppeth','comes down'; 'blest','joyful'}; [rows cols] = size(dict); for row = 1:rows if strcmpi(dict{row,1}, word) word = dict{row,2} break; end end end

______

Mercy.txt

______

The quality of mercy is not strain'd, It droppeth as the gentle rain from heaven Upon the place beneath: it is twice blest; It blesseth him that gives and him that takes: 'Tis mightiest in the mightiest: it becomes The throned monarch better than his crown; His sceptre shows the force of temporal power, The attribute to awe and majesty, Wherein doth sit the dread and fear of kings; But mercy is above this sceptred sway; It is enthroned in the hearts of kings, It is an attribute to God himself; And earthly power doth then show likest God's When mercy seasons justice.

************** Now Some Structure **************** % % Structures and Structure Arrays % % 3 ways to make a structure: % One field at a time % the dreaded struct(...) function % custom function

########### good file to work with ######## ####### but needs structure ############## clear clc fh = fopen('movies.txt','r'); line = fgetl(fh) for loop = 1:5

line = fgetl(fh)

[token rest] = strtok(line, char(9)) end ##########################################

###### Let’s have Structure ############## function joneses clc

fred.first = 'Fred'; fred.last = 'Jones'; fred.grad = false; fred.age = 42; date.year = 1968; date.month = 'Feb'; date.day = 30; fred.birth = date;

sally = fred; sally.first = 'Sally'; sally.birth.day = 31; date.year = 1969; triplets = struct('first', {'A', 'B', 'C'}, ... 'last', 'Jones', ... 'grad', {false true false}, ... 'age', 41, ... 'birth', date); address = fred; address = [address sally]; address = [address triplets]; for person = address show_person(person) end fprintf('now, in order\n') firsts = {address.first}; [~, order] = sort(firsts); for ndx = 1:length(order) it = order(ndx); show_person(address(it)) end end function show_person(p) fprintf('%s %s\n', p.first, p.last) end

Recommended publications