Connecting Tech Pros Worldwide Forums | Help | Site Map

Newbie question: casting problem

Newbie
 
Join Date: Mar 2008
Location: Hamburg
Posts: 1
#1: Mar 12 '08
Hello I am starting to use Python.
I found a nice little example for subsituting and splitting texts and counting words separated by defined expressions (in the example , and blanks). Unfotunately there is an error in this example regarding the casting of strings: (see the code below):


#zerleg.py
import re
try:
fh=open('input.txt','r')
summe=0
n=0
while 1:
Zeile = fh.readline()
if Zeile =='':break
mZeile = re.sub('[ ,\r\n]{1,}$','',Zeile)
Wert = re.split('[ ,]{1,}',mZeile)
for i in range(len(Wert)):
print'Wert:', Wert[i], '\n', len(Wert)
summe = summe + float(Wert[i])
n=n+len(Wert)
print"Summe: ", summe, \
'\nEingabedaten: ', n, \
'\nMittelwert : ', summe/n, '\n'
fh.close
except IOError, (errno, strerror):
print'Datei input.txt nicht lesbar. \n', \
'Fehlernummer:', errno, '\n', \
'Fehlermeldung: ', strerror

Using the example above I am getting the following error message:

--> invalid literal for float(): ... fisrt word in file input.txt

The content of my input.txt is:
ba,nd001
hugo HiHo,002
alter ego 009
ha, what 006
003
END !? NO 010

Any idea how this casting problem could be solved?


Bye Guncrew



jlm699's Avatar
Needs Regular Fix
 
Join Date: Jul 2007
Location: Durham, NC
Posts: 313
#2: Mar 12 '08

re: Newbie question: casting problem


Quote:

Originally Posted by guncrew

Expand|Select|Wrap|Line Numbers
  1.         summe = summe + float(Wert[i])

You cannot float cast any characters. .. are you trying to count the number of words? If so, just simply use:
Expand|Select|Wrap|Line Numbers
  1. summe += 1
Reply