Why did the order of my script give a Divide by Zero error? - divide-by-zero

I'm working on some beginner Python exercises. I have the following, working code:
# Use the file name mbox-short.txt as the file name
fname = raw_input("Enter file name: ")
fh = open(fname)
inp=fh.readlines()
count=0
total=0.0
for line in inp:
line=line.rstrip()
if not line.startswith("X-DSPAM-Confidence:"):
continue
value=line[19:]
value=float(value)
count=count+1
total=total + value
print "Average spam confidence:",total/count
When I first wrote this, I put the "count" line before the "value" line like this:
# Use the file name mbox-short.txt as the file name
fname = raw_input("Enter file name: ")
fh = open(fname)
inp=fh.readlines()
count=0
total=0.0
for line in inp:
line=line.rstrip()
if not line.startswith("X-DSPAM-Confidence:"):
continue
count=count+1
value=line[19:]
value=float(value)
total=total + value
print "Average spam confidence:",total/count
This resulted in a divide by zero error. Why?

Related

How to read by the number at each iteration of the loop in Ruby?

How to read by the number at each iteration of the loop? Dynamic work is important, (not once to read the entire line and convert to an array), at each iteration, take one number from the file string and work with it. How to do it right?
input.txt :
5
1 7 5 2 3
Work with 2nd line of the file.
fin = File.open("input.txt", "r")
fout = File.open("output.txt", "w")
n = fin.readline.to_i
heap_min = Heap.new(:min)
heap_max = Heap.new(:max)
for i in 1..n
a = fin.read.to_i #code here <--
heap_max.push(a)
if heap_max.size > heap_min.size
tmp = heap_max.top
heap_max.pop
heap_min.push(tmp)
end
if heap_min.size > heap_max.size
tmp = heap_min.top
heap_min.pop
heap_max.push(tmp)
end
if heap_max.size == heap_min.size
heap_max.top > heap_min.top ? median = heap_min.top : median = heap_max.top
else
median = heap_max.top
end
fout.print(median, " ")
end
If you're 100% sure that your file separate numbers by space you can try this :
a = fin.gets(' ', -1).to_i
Read the 2nd line of a file:
line2 = File.readlines('input.txt')[1]
Convert it to an array of integers:
array = line2.split(' ').map(&:to_i).compact

Displaying only certain text from file - Visual Basic

I want to only display numbers in a text box that i have. At the moment my code reads the text file and adds all the code to the textbox and not only the needed text(which are numbers).
tbRecipient.Text = My.Computer.FileSystem.ReadAllText("filepath")
if anyone can point me in the right direction and let me know how i would go around this problem, that would be great.
I have a file containing:
Steve, 017876
Alan, 098578
...
I want to list only the numbers into a text box once i have got them from the file.
To do this i am using:
Dim i As Integer
For i = 0 To cbRecipients.CheckedItems.Count - 1
My.Computer.FileSystem.WriteAllText("filepath", cbRecipients.CheckedItems.Item(i) & vbCrLf, True)
Next
frmHome.myFunction()
Then under myFunction() is:
tbRecipient.Text = My.Computer.FileSystem.ReadAllText("filepath")
You can use this function:
Function GetFileColumnContents(s_Path As String, ColumnNumber As Long, ColumnDelimiter As String, Optional s_OutputDelimiter As String) As String
On Error GoTo ErrHandler
Open s_Path For Input As #1 'Open the txt file for readin as Temporary File Number 1
Do While Not EOF(1) 'Read line bu line until end of file
Line Input #1, Mystring 'Store the line value in Mystring
GetFileColumnContents = GetFileColumnContents & s_OutputDelimiter & Split(Mystring, ColumnDelimiter)(ColumnNumber - 1) 'process the string
Loop
ErrHandler:
Close #1
End Function
Call in subrutine:
tbRecipient.Text = GetFileColumnContents("filepath", 2, ",", vbCrLf)
Edit: The linenum = linenum + 1 was not neccesary in the function (edited above)
s_Path : is path to the txt file (like "C:\Test.txt")
ColumnNumber: is the column in the text file. If the data looks like:
A, 123, red
B, 456, blue
then ColumnNumber 1 are letters, ColumnNumber 2 are numbers and 3 are colors.
(ColumnNumber - 1) is there because first part of split has index 0, but the ColumnNumber is 1
split("A, 123, red",",")(0) 'results to "A"
split("A, 123, red",",")(1) 'results to " 123"
If you want to list the items from text file column 2 and in the result separated by comma then call the function with comma as last argument:
tbRecipient.Text = GetFileColumnContents("filepath", 2, ",", ",")

UNIX find every line in a text file that contains a string and output last word of these

I have a text file that contains a number of lines that starts with "# Control Point No"
I managed to get an output of only these lines by doing
grep '# Control Point No'
Now I want only to keep the last word of all these line.
The lines look like
"# Control Point No 39217: 1.52520046527084"
So I want to output only the last numbers as 1.52520046527084
and then:
-find lowest value
-find highest value
-calculate average value
All this I want to do is not all included in the post title, sorry
Thanks
Python is your friend:
#!/usr/bin/python
import re, fileinput, sys
numlines = 0
lowest = sys.float_info.max
highest = sys.float_info.min
total = 0.0
for line in fileinput.input():
m = re.match(r'# Control Point No (\d+): (.+)', line)
if m:
value = float(m.group(2))
numlines += 1
if value < lowest:
lowest = value
if value > highest:
highest = value
total += value
print "lowest=", lowest, ", highest=", highest, ", average=", (total / numlines)
$ chmod 0755 procdata.py
$ ./procdata.py < testdata
lowest= 1.0 , highest= 67.9 , average= 7.31550797863

Ruby csv for each - clean up characters?

I have the following code which reads each line of a csv and cleans up each row. The rows are all path\ file name directories. I am having an issue where the script cannot find a path\file because the file name has a - in it. The - (dash) is read by ruby as \x96 . Does anyone know how to get it to not do that, and to read the - as a dash?
This is what I have, but it is not working:
CSV.foreach("#{batch_File_Dir_sdata}") do |ln|
line_number += 1
pathline = ln.to_s
log_linemsg = "Source #{line_number}= #{pathline}"
log_line = ["#{$cname}","#{log_linemsg}","","",]
puts log_linemsg
insert_logitems(connection, table_namelog, log_line)
if pathline.include?("\\")
cleanpath = pathline.gsub!("\\\\","\\")
#cleanpath = cleanpath.gsub!("[","")
#cleanpath = cleanpath.gsub!("]","")
cleanpath.gsub!("\"","")
#THIS IS THE LINE WHERE I AM TRYING TO FIX THE ISSUE
cleanpath.gsub!("\\x96","\-")
cleanpath.slice!(0)
cleanpath.chop!
#puts "Clean path - has backslash\n#{cleanpath}"
else
cleanpath = pathline
#puts "#{cleanpath}"
#puts "Clean path - has NO backslash\n#{cleanpath}"
end
Any help would be greatly appreciated.

File writing : carriage return and Tab

Hi i'm new to VB6 and i want to implement this : when a user is logged he enters his name and password , i should write it in a file.
Here's the file "authentification.txt" : it has the form of username password
bill hope
jessica 1234567
jhon 7654321
Here's the code :
Open "c:\authentification.txt" For Binary As #1
x = txtidentifiant.Text
y = txtmotdepasse.Text
Do While Not EOF(1)
Line Input #1, l
If l <> " " Then
Put 1, i, x & vbNewLine
Put 1, i + 1, y & vbNewLine
Else
//here i want to implement a carriage return in the file #1
End If
Loop
My problem is :that the file if filled like this : bhope
and it writes only the first line
You should use the Input and Print statements. They read and write comma delimited files, and are designed to be used in pairs, for just such an application.
Here's the new code :
Open "c:\authentification.txt" For Append As #1
x = txtidentifiant.Text
y = txtmotdepasse.Text
Print #1, x
Print #1, y
Close #1

Resources