0

我想寻求帮助来做一个计算器,它可以识别 Python 中的英文单词和数字,但现在使用 PLY (Python Lex-Yacc)

数字和运算符可以用英语单词写成字符串的两种形式给出,“加号”=“+”,“二”=2,“12”=112,等等。

一个例子可能是这些条目:

“二十五除以 5”或“25 / 5”或“二十五除以五”

结果应该是相同的,一个数字 5(不是字符串)。

“-3 乘以 4”将给出 -12

除以 0 将给出“错误”“34 除以 0”将给出“错误”

如果我键入数学符号或键入文本或混合,这应该适用于几个基本运算符“-”、“+”、“x”和“/”(减号、加号、时间和除以)。

以下是我的代码的一些部分:

# ------- Calculator tokenizing rules

tokens = (
    'NAME','NUMBER', 'times', 'divided_by', 'plus', 'minus'
)

literals = ['=','+','-','*','/', '(',')']

t_ignore = " \t"

t_plus    = r'\+'
t_minus   = r'-'
t_times   = r'\*'
t_divided_by  = r'/'
t_NAME    = r'[a-zA-Z_][a-zA-Z0-9_]*'

  precedence = (
    ('left','+','-'),
    ('left','plus','minus'),
    ('left','times','divided_by'),
    ('left','*','/'),
    ('right','UMINUS'),
)

#这里改变了赋值 def p_statement_assign(p): 'statement : expression times divide_by plus minus expression' variables[p[1]] = p[3] p[0] = None

def p_statement_expr(p):
    'statement : expression'
    p[0] = p[1]

def p_expression_binop(p):
    '''expression : expression '+' expression
                  | expression 'plus' expression
                  | expression '-' expression
                  | expression 'minus' expression
                  | expression '*' expression
                  | expression 'times' expression
                  | expression 'divided_by' expression
                  | expression '/' expression'''
    if p[2] ==   '+'  : p[0] = p[1] + p[3]
    elif p[2] == '-': p[0] = p[1] - p[3]
    elif p[2] == '*': p[0] = p[1] * p[3]
    elif p[2] == '/': p[0] = p[1] / p[3]

我的代币是否有错误的定义?我怎么知道这个数字可以用英文字母或数字介绍?

表达式(p[2] == '+' : p[0] = p[1] + p[3])必须有一个字符。为什么用这种形式写无效p[2] == 'plus' : p[0] = p[1] + p[3]


我已经添加了 sfk 建议的代码,但我仍然无法识别输入为文本的数字和运算符,用英文单词。

Generating LALR tables
WARNING: 12 shift/reduce conflicts
 Enter your input: calc > one + two
Undefined name 'one'
Undefined name 'two'
P1 is :  0
 Enter your input: calc > 1+2
P1 is :  3
3
 Enter your input: calc > 1 plus 2
Syntax error at 'plus'
P1 is :  2
2

你知道我做错了什么吗?

4

1 回答 1

1

一、为英文单词添加token定义

t_plustext    = r'plus'

将这些新令牌添加到tokens

tokens = (
    'NAME','NUMBER', 'times', 'divided_by', 'plus', 'minus', 'plustext', ....
)

最后,以这种方式在语法中使用这些新标记:

def p_expression_binop(p):
    '''expression : expression '+' expression
                  | expression plustext expression
    '''

更新:这是语法的一个工作子集

#!/usr/bin/python

from __future__ import print_function

import sys
import ply.lex as lex
import ply.yacc as yacc

# ------- Calculator tokenizing rules

tokens = (
    'NUMBER', 'times', 'divided_by', 'plus', 'minus', 'plustext',
    'one', 'two', 'three',
)

literals = ['=','+','-','*','/', '(',')']

t_ignore = " \t\n"

t_plustext    = r'plus'
t_plus    = r'\+'
t_minus   = r'-'
t_times   = r'\*'
t_divided_by  = r'/'
t_one = 'one'
t_two = 'two'
t_three = 'three'

def t_NUMBER(t):
    r'\d+'
    try:
        t.value = int(t.value)
    except ValueError:
        print("Integer value too large %d", t.value)
        t.value = 0
    return t

precedence = (
    ('left','+','-','plustext'),
    ('left','times','divided_by'),
    ('left','*','/'),
)


def p_statement_expr(p):
    'statement : expression'
    p[0] = p[1]
    print(p[1])

def p_expression_binop(p):
    '''expression : expression '+' expression
                  | expression plustext expression
                  | expression '-' expression
                  | expression '*' expression
                  | expression '/' expression'''
    if p[2] ==   '+'  : p[0] = p[1] + p[3]
    elif p[2] == '-': p[0] = p[1] - p[3]
    elif p[2] == '*': p[0] = p[1] * p[3]
    elif p[2] == '/': p[0] = p[1] / p[3]
    elif p[2] == 'plus': p[0] = p[1] + p[3]

def p_statement_lit(p):
    '''expression : NUMBER
          | TXTNUMBER
    '''
    p[0] = p[1]

def p_txtnumber(p):
    '''TXTNUMBER : one
         | two
         | three
    '''
    p[0] = w2n(p[1])

def w2n(s):
    if s == 'one': return 1
    elif s == 'two': return 2
    elif s == 'three': return 3
    assert(False)
    # See http://stackoverflow.com/questions/493174/is-there-a-way-to-convert-number-words-to-integers-python for a complete implementation

def process(data):
    lex.lex()
        yacc.yacc()
        #yacc.parse(data, debug=1, tracking=True)
        yacc.parse(data)

if __name__ == "__main__":
        data = open(sys.argv[1]).read()
        process(data)
于 2013-09-14T14:00:20.300 回答