-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslides-09-02.qmd
254 lines (190 loc) · 4.66 KB
/
slides-09-02.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
---
title: "files and strings (slides)"
format: revealjs
slide-number: true
df-print: kable
---
# CSc 110 - files and strings
## String methods
- `string.strip(chars)` -- removes any of the characters in chars from the beginning or end of string, returns a string
- `string.split(chars)` -- splits string at the chars, returns a list
- `string.lower(string)` -- forces all characters to lowercase, returns a string
## Write a function
Its name is `sum_all` that takes a string `filename` as argument.
It reads the file with `filename` and iterates over each line in [the file](data/numbers.txt), stripping the line breaks, casting each line as integer (assume each line is a single number), summing each number to a total variable. Return the total.
Name your file `sum_numbers.py` and submit to Gradescope.
```{python}
#| echo: true
#| eval: false
assert sum_all("numbers.txt") == 15
```
## Write a function -- solution
```{python}
#| echo: true
#| eval: true
def sum_all(file_name):
total = 0
for line in open(file_name, "r"):
number = int(line.strip("\n"))
total += number
return total
def main():
assert sum_all("numbers.txt") == 15
main()
```
## Modes
- To read a file:
- Use **'r'** for reading the contents of a file
- To write to a file: use
- Use **'a'** to append to the existing file content
- Use **'w'** to write to a file, and replace existing content
## Writing to a file
- After you have opened the file in either **'a'** or **'w'** mode
```
a_file = open(file_name, mode)
```
- Use the **write** function to write text content to the file
```
a_file.write('put this content in a file')
```
- When finished writing, **close** the file **a_file.close()**
## Create a file
words.txt
```{html}
Let us start a story.
```
## Evaluate the code
```{python}
#| echo: true
#| eval: true
words = open('words.txt', 'w')
words.write('The slow wolf')
words.write('jumped over')
words.write('the bear')
words.close()
```
## Evaluate the code
```{python}
#| echo: true
#| eval: true
words = open('words.txt', 'w')
words.write('The slow wolf')
words.write('jumped over')
words.write('the bear')
words.close()
```
words.txt
```{html}
The slow wolfjumped overthe bear
```
## Evaluate the code
```{python}
#| echo: true
#| eval: true
words = open('words.txt', 'w')
words.write('The slow wolf\n')
words.write('jumped over\n')
words.write('the bear')
words.close()
```
## Evaluate the code
```{python}
#| echo: true
#| eval: true
words = open('words.txt', 'w')
words.write('The slow wolf\n')
words.write('jumped over\n')
words.write('the bear')
words.close()
```
words.txt
```{html}
The slow wolf
jumped over
the bear
```
## Evaluate the code -- continued
```{python}
#| echo: true
#| eval: true
words = open('words.txt', 'a')
words.write(' The quick fox\n')
words.write('jumped over\n')
words.write('the bear')
words.close()
```
## Evaluate the code -- continued
```{python}
#| echo: true
#| eval: true
words = open('words.txt', 'a')
words.write(' The quick fox\n')
words.write('jumped over\n')
words.write('the bear')
words.close()
```
words.txt
```{html}
The slow wolf
jumped over
the bear The quick fox
jumped over
the bear
```
## Combining dictionary with write
```{python}
#| eval: false
#| echo: true
info = {"a": 2, "b": 5, "c": 0}
output = open("count.txt", "w")
for key, value in info.items():
output.write(key + ", " + str(value) + "\n")
output.write("end")
output.close()
```
count.txt
```{html}
a, 2
b, 5
c, 0
end
```
## Write two functions
* Both functions takes a string `file_name` as argument:
* `count_words` count frequency of each lowercase word, return a dictionary.
* `write_word_count` call `count_words`, iterate it and write a comma separated file ("out_" + `file_name`).
* [Download test file](data/alien.txt)
Name file as `read_and_write.py`, submit for attendance.
Test case:
```{python}
#| eval: false
#| echo: true
write_word_count("alien.txt")
# writes out out_alien.txt with word counts
```
## Write two functions -- solution
```{python}
#| eval: true
#| echo: true
def count_words(file_name):
f = open(file_name, "r")
counts = {}
for line in f:
words = line.strip("\n").split(" ")
for w in words:
lower_case_w = w.lower()
if lower_case_w not in counts:
counts[lower_case_w] = 1
else:
counts[lower_case_w] += 1
return counts
def write_word_count(file_name):
count_dict = count_words(file_name)
output_file = open("out_" + file_name, "w")
for key, value in count_dict.items():
output_file.write(key + "," + str(value) + "\n")
output_file.close()
def main():
write_word_count("alien.txt")
main()
```