Computer Science

# Lab 14 - More Strings

## Activities

### random_asterisks.py

Write a function random_asterisks(sentence) that randomly replaces 30% of the words in sentence with a string of asterisks that is the same length of the corresponding word being replaced.

For example:

random_asterisks("About three of ten words in this sentence are asterisks")

Could return:

"About ***** of ten ***** in this sentence are *********"

### sum_integers.py

Write a function sum_integers(filename) that returns the sum of all of the integers (not digits) that are found in a given file.

For example:

example_file.txt

I had 3 slices of pizza for dinner at 8 o'clock this morning
2048 is a fun game

The function

sum_integers("example_file.txt")

Would return:

2101

Because 3 + 8 + 42 + 2048 = 2101

### divide_numbers.py

Write a function divide_numbers(input_file, output_file) whereinput_file is a comma-delimited file. Comma-delimited is a common type of data format where each data point is separated by a comma (example below).

Every data point in input_file is either a number or “NaN”. “NaN” means “Not a number” and is used to indicate that there is no numeric data available for that data point (such as when data is missing).

The function divide_numbers(input_file, output_file) should write an output_file that has the same contents as input_file except every number is divided by 100. Do not modify the “NaN”s.

Input

42,50,33
NaN,60,NaN
12,2,NaN

Output

0.42,0.5,0.33
NaN,0.6,NaN
0.12,0.02,NaN

### replace_word.py

Write a function replace_word(input_file, output_file, new_word) that randomly chooses a word from input_file, replaces every occurence of that chosen word with new_word, and writes the result to a new output_file.

example_input.txt

taco cat burrito
burrito bean taco
bean cat taco
burrito cat taco

The function:

replace_word("example_input.txt", "example_output.txt", "meow")

Could write the file:

example_output.txt

taco meow burrito
burrito bean taco
bean meow taco
burrito meow taco

Note: In this case the function randomly chose to replace “cat” with “meow”. If we were to run the function again it could randomly choose to replace any of the words (burrito, bean, taco, or cat) with “meow”.