Newbie question: casting problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • guncrew
    New Member
    • Mar 2008
    • 1

    Newbie question: casting problem

    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
    Contributor
    • Jul 2007
    • 314

    #2
    Originally posted by guncrew
    [CODE=python]
    summe = summe + float(Wert[i])[/CODE]
    You cannot float cast any characters. .. are you trying to count the number of words? If so, just simply use:
    [CODE=python]summe += 1[/CODE]

    Comment

    Working...