<cut> Having read through the many threads on this topic on comp.lang.python I realise and understand that modern programs' input generally requires thought and customization from the program author. However, we strongly feel there should be an equivalent to Pascal's readln (which is basically C's scanf but without the formatting strings) for simple, generally numerical, whitespace-separated input. <cut>
I know the course is ended now, but did you come up with a satisfactory solution? Here is an alternative which focuses on the numbers rather than the separators: you split out the numbers and then evaluate them as floats or ints. A "~" preceeds each of the physical lines in the script below so if the file gets mangled you can reconstruct it by removing spurious newlines until each line once again starts with a "~". #### ~ def ninput(n = None, fin = None, prompt = ''): ~ "Return n (or all) numbers from a line read from the keyboard (or file object)." ~ ~ import re ~ #iflo matches exponentials, floats, integers (in that order) ~ iflo=re.compile(r'([0-9]*\.?[0-9]+[eE][-+]?[0-9]+|[0-9]+\.?[0-9]*[eE][-+]?[0-9]+|[0-9]*\.[0-9]+|[0-9]+\.[0-9]*|[1-9][0-9]*)') ~ ~ if fin == None: # get the string ~ s = raw_input(prompt) ~ else: ~ s = fin.readline() ~ s=re.split(iflo,s) #split it apart, retaining the matched numbers ~ s=filter(lambda x:iflo.match(x),s) #keep only the numbers ~ for i in range(len(s)): #convert them to numerics ~ try: ~ s[i]=int(s[i]) ~ except: ~ s[i]=float(s[i]) ~ if n==None: ~ return s #send them all back as a list ~ else: ~ return s[:n]+[None]*(n-len(s)) #send back the number requested; send None for missing values #### Here are some examples from the interpreter:
ninput() # it doesn't matter what is on the line--the numbers are split out. This is the 1st number and here are 2 more: 3.4, 5.6 [1, 2, 3.3999999999999999, 5.5999999999999996] ninput(2) 1,6.02e23 [1, 6.02e+23] ninput(3) #if there aren't enough, None's are returned 1 [1, None, None] x,y,z = ninput(3) (1,2) and (3,4) were the coordinates print x,y,z 1 2 3
/c
participants (1)
-
Christopher Smith