2014-03-31 26 views
0

我想弄清楚如何創建類型並根據這些類型轉換用戶輸入。 例如:在Python中解析/創建類型

用戶輸入:5

5是類型數 5被添加到列表中

用戶輸入的:3.5

3.5是類型數 3.5被添加到的清單

用戶輸入::true:

:true:是鍵入布爾值 :true:獲得添加到列表

我希望我的程序能夠將數字5轉換爲int然後將其放在堆棧上,然後將它放到一個float上,然後將它放到堆棧上並且知道:true:具有True值。

這裏是我試過,但迄今爲止沒有工作它應該的方式:

#!/util/bin/python 
import re 
import shlex 
stack = [] 

tokens = (
    ('STRING', re.compile('"[^"]+"')), # longest match 
    ('NAME', re.compile('[a-zA-Z_]+')), 
    ('SPACE', re.compile('\s+')), 
    ('NUMBERD', re.compile('\d.')), 
    ('NUMBERI', re.compile('\d+')), 
    ('TRUE', re.compile(':true:')), 
    ('FALSE', re.compile(':false:')), 
) 

def main(): 


    while 1: 
     inp = input('INPUT> ') 
     push(inp,stack) #Push User Input unto stack 
     printStack(stack) #Print Stack 
     quit(inp,stack) #Exit program if prompted 




def push(s,list): 
    tokens = shlex.split(s, posix=False) 
    for token in tokens: 
     if type(s) == 'NUMBERI': 
      list.append(int(token)) 
     elif type(s) == 'NUMBERD': 
      list.append(float(token)) 
     else: 
      list.append(token) 

    return list 

def printStack(stack): 
    for index in stack[::-1]: 
     print (index) 



def quit (x, stack): 
    if x == "quit": 
     stack.pop() 
     exit(0) 


def type(s): 
    i = 0 
    lexeme = [] 
    while i < len(s): 
     match = False 
     for token, regex in tokens: 
      result = regex.match(s, i) 
      if result: 
       return(token) 
       i = result.end() 
       match = True 
       break 
     if not match: 
      raise Exception('lexical error at {0}'.format(i)) 




def add (x,y): 
    return(x + y) 

def sub (x,y): 
    return(x - y) 

def mul (x,y): 
    return(x * y) 

def div (x,y): 
    return(x/y) 


main() 

回答

0

使用ast.literal_eval,安全地計算一個字符串表達式。

演示:

>>> from ast import literal_eval 
>>> a = literal_eval('5') 
>>> b = literal_eval('3.5') 
>>> c = literal_eval('True') 
>>> [e, type(e).__name__ for e in (a, b, c)] 
[(5, 'int'), (3.5, 'float'), (True, 'bool')] 
+0

完美!但我如何轉換爲可以說一個浮點數或整數? @亞瑟桑頓 –

+0

@MannyO我不明白。它們在評估時會自動轉換爲相應的類型。 –

+0

哦,所以他們得到轉換,並推到堆棧綁定到他們的新類型? @Alex Thornton –

0

嘗試:

push(str(inp),stack) #Push User Input unto stack 
相關問題