In: Computer Science
original code:
filename = "CCL-mbox-tiny.txt"
with open(filename, 'r') as f:
for line in f.readlines():
print(line.strip())
1. Now modify the code above to print the number of lines in the
file, instead of printing the lines themselves. You'll need to
increment a variable each time through the loop and then print it
out afterwards.
There should be **332** lines.
2. Next, we'll focus on only getting lines addressing `X-DSPAM-Confidence:`. We do this by including an `if` statement inside the `for` loop. This is a very common pattern in computing used to search through massive amoutns of data.
You need to edit line 4 of the code below to only print lines which begin with `X-DSPAM-Confidence:` You know you got it working if in your output there are only **5** rows.
filename = "CCL-mbox-tiny.txt"
with open(filename, 'r') as f:
for line in f.readlines():
if ?:
print(line.strip())
3. The final step is to figure out how to parse out the confidence value from the string. For example for the given line: X-DSPAM-Confidence: 0.8475 we need to get the value 0.8475 as a float.
The strategy here is to replace X-DSPAM-Confidence: with an empty string, then calling the float() function to convert the results to a float.
Now Try It
Write code to parse the value 0.8475 from the text string 'X-DSPAM-Confidence: 0.8475'.
line = 'X-DSPAM-Confidence: 0.8475'
number = #TODO remove 'X-DSPAM-Confidence:' , then convert to a
float.
print (number)
Python Language
1.
#variable for storing number of lines
count =0
#assigning file name in a variable
filename = "CCL-mbox-tiny.txt"
#opening file name
with open(filename, 'r') as f:
#reading line by line
for line in f.readlines():
#incrementing number of lines
count = count+1
#prints count of lines
print(count)
2.
#variable for storing number of lines
count =0
#assigning file name in a variable
filename = "CCL-mbox-tiny.txt"
#opening file name
with open(filename, 'r') as f:
# reading line by line
for line in f.readlines():
#checks wether line starts with "X-DSPAM-Confidence:"
if line.split(" ")[0] =="X-DSPAM-Confidence:":
#incrementing number of lines
count = count+1
#prints count of lines
print(count)
3.
#assigning string to a variable
line = "X-DSPAM-Confidence: 0.8475"
#extracts value and converts it to float
number = float(line.split(" ")[1])
#prints number
print(number)
#prints type of number
print(type(number))
i hope the answer is clear and satisfactory
if you have any doubts feel free to ask in comment section
please give me thumbs up