句法分析#

解析函数参考#

sympy.parsing.sympy_parser.parse_expr(s: str, local_dict: ~typing.Dict[str, ~typing.Any] | None = None, transformations: ~typing.Tuple[~typing.Callable[[~typing.List[~typing.Tuple[int, str]], ~typing.Dict[str, ~typing.Any], ~typing.Dict[str, ~typing.Any]], ~typing.List[~typing.Tuple[int, str]]], ...] | str = (<function lambda_notation>, <function auto_symbol>, <function repeated_decimals>, <function auto_number>, <function factorial_notation>), global_dict: ~typing.Dict[str, ~typing.Any] | None = None, evaluate=True)[源代码]#

Converts the string s to a SymPy expression, in local_dict.

参数:

s :结构

要分析的字符串。

local_dict :dict,可选

解析时要使用的局部变量字典。

global_dict :dict,可选

全局变量词典。默认情况下,初始化时使用 from sympy import * ;提供此参数以覆盖此行为(例如,解析 "Q & S"

transformations : tuple or str

A tuple of transformation functions used to modify the tokens of the parsed expression before evaluation. The default transformations convert numeric literals into their SymPy equivalents, convert undefined variables into SymPy symbols, and allow the use of standard mathematical factorial notation (e.g. x!). Selection via string is available (see below).

评价 :bool,可选

如果为False,参数的顺序将保持在字符串中的顺序,并且通常会发生的自动简化被抑制。(见示例)

实例

>>> from sympy.parsing.sympy_parser import parse_expr
>>> parse_expr("1/2")
1/2
>>> type(_)
<class 'sympy.core.numbers.Half'>
>>> from sympy.parsing.sympy_parser import standard_transformations,\
... implicit_multiplication_application
>>> transformations = (standard_transformations +
...     (implicit_multiplication_application,))
>>> parse_expr("2x", transformations=transformations)
2*x

当evaluate=False时,某些自动简化将不会发生:

>>> parse_expr("2**3"), parse_expr("2**3", evaluate=False)
(8, 2**3)

此外,参数的顺序不会成为规范的。此功能允许用户准确地知道表达式是如何输入的:

>>> a = parse_expr('1 + x', evaluate=False)
>>> b = parse_expr('x + 1', evaluate=0)
>>> a == b
False
>>> a.args
(1, x)
>>> b.args
(x, 1)

Note, however, that when these expressions are printed they will appear the same:

>>> assert str(a) == str(b)

As a convenience, transformations can be seen by printing transformations:

>>> from sympy.parsing.sympy_parser import transformations
>>> print(transformations)
0: lambda_notation
1: auto_symbol
2: repeated_decimals
3: auto_number
4: factorial_notation
5: implicit_multiplication_application
6: convert_xor
7: implicit_application
8: implicit_multiplication
9: convert_equals_signs
10: function_exponentiation
11: rationalize

The T object provides a way to select these transformations:

>>> from sympy.parsing.sympy_parser import T

If you print it, you will see the same list as shown above.

>>> str(T) == str(transformations)
True

Standard slicing will return a tuple of transformations:

>>> T[:5] == standard_transformations
True

So T can be used to specify the parsing transformations:

>>> parse_expr("2x", transformations=T[:5])
Traceback (most recent call last):
...
SyntaxError: invalid syntax
>>> parse_expr("2x", transformations=T[:6])
2*x
>>> parse_expr('.3', transformations=T[3, 11])
3/10
>>> parse_expr('.3x', transformations=T[:])
3*x/10

As a further convenience, strings 'implicit' and 'all' can be used to select 0-5 and all the transformations, respectively.

>>> parse_expr('.3x', transformations='all')
3*x/10
sympy.parsing.sympy_parser.stringify_expr(s: str, local_dict: Dict[str, Any], global_dict: Dict[str, Any], transformations: Tuple[Callable[[List[Tuple[int, str]], Dict[str, Any], Dict[str, Any]], List[Tuple[int, str]]], ...]) str[源代码]#

转换字符串 s 到Python代码,在 local_dict

一般来说, parse_expr 应该使用。

sympy.parsing.sympy_parser.eval_expr(code, local_dict: Dict[str, Any], global_dict: Dict[str, Any])[源代码]#

计算由生成的Python代码 stringify_expr .

一般来说, parse_expr 应该使用。

sympy.parsing.maxima.parse_maxima(str, globals=None, name_dict={})[源代码]#
sympy.parsing.mathematica.parse_mathematica(s)[源代码]#

Translate a string containing a Wolfram Mathematica expression to a SymPy expression.

If the translator is unable to find a suitable SymPy expression, the FullForm of the Mathematica expression will be output, using SymPy Function objects as nodes of the syntax tree.

实例

>>> from sympy.parsing.mathematica import parse_mathematica
>>> parse_mathematica("Sin[x]^2 Tan[y]")
sin(x)**2*tan(y)
>>> e = parse_mathematica("F[7,5,3]")
>>> e
F(7, 5, 3)
>>> from sympy import Function, Max, Min
>>> e.replace(Function("F"), lambda *x: Max(*x)*Min(*x))
21

Both standard input form and Mathematica full form are supported:

>>> parse_mathematica("x*(a + b)")
x*(a + b)
>>> parse_mathematica("Times[x, Plus[a, b]]")
x*(a + b)

To get a matrix from Wolfram's code:

>>> m = parse_mathematica("{{a, b}, {c, d}}")
>>> m
((a, b), (c, d))
>>> from sympy import Matrix
>>> Matrix(m)
Matrix([
[a, b],
[c, d]])

If the translation into equivalent SymPy expressions fails, an SymPy expression equivalent to Wolfram Mathematica's "FullForm" will be created:

>>> parse_mathematica("x_.")
Optional(Pattern(x, Blank()))
>>> parse_mathematica("Plus @@ {x, y, z}")
Apply(Plus, (x, y, z))
>>> parse_mathematica("f[x_, 3] := x^3 /; x > 0")
SetDelayed(f(Pattern(x, Blank()), 3), Condition(x**3, x > 0))

分析转换参考#

转换是接受参数的函数 tokens, local_dict, global_dict 并返回已转换标记的列表。它们可以通过将函数列表传递给 parse_expr() 并按给定的顺序应用。

sympy.parsing.sympy_parser.standard_transformations: Tuple[Callable[[List[Tuple[int, str]], Dict[str, Any], Dict[str, Any]], List[Tuple[int, str]]], ...] = (<function lambda_notation>, <function auto_symbol>, <function repeated_decimals>, <function auto_number>, <function factorial_notation>)#

的标准转换 parse_expr() . 将调用插入 SymbolInteger ,以及其他SymPy数据类型,并允许使用标准的阶乘表示法(例如。 x!

sympy.parsing.sympy_parser.split_symbols(tokens: List[Tuple[int, str]], local_dict: Dict[str, Any], global_dict: Dict[str, Any])[源代码]#

拆分符号名称以进行隐式乘法。

旨在让表达 xyz 被解析为 x*y*z . 不会拆分希腊字符名,所以 thetanot 成为 t*h*e*t*a . 一般应与 implicit_multiplication .

sympy.parsing.sympy_parser.split_symbols_custom(predicate: Callable[[str], bool])[源代码]#

创建一个分解符号名称的转换。

predicate 如果要拆分符号名称,则应返回True。

例如,要保留默认行为但避免拆分某些符号名,可以使用如下谓词:

>>> from sympy.parsing.sympy_parser import (parse_expr, _token_splittable,
... standard_transformations, implicit_multiplication,
... split_symbols_custom)
>>> def can_split(symbol):
...     if symbol not in ('list', 'of', 'unsplittable', 'names'):
...             return _token_splittable(symbol)
...     return False
...
>>> transformation = split_symbols_custom(can_split)
>>> parse_expr('unsplittable', transformations=standard_transformations +
... (transformation, implicit_multiplication))
unsplittable
sympy.parsing.sympy_parser.implicit_multiplication(tokens: List[Tuple[int, str]], local_dict: Dict[str, Any], global_dict: Dict[str, Any]) List[Tuple[int, str]][源代码]#

使乘法运算符在大多数情况下是可选的。

先用这个 implicit_application() ,否则表达式如下 sin 2x 将被解析为 x * sin(2) 而不是 sin(2*x) .

实例

>>> from sympy.parsing.sympy_parser import (parse_expr,
... standard_transformations, implicit_multiplication)
>>> transformations = standard_transformations + (implicit_multiplication,)
>>> parse_expr('3 x y', transformations=transformations)
3*x*y
sympy.parsing.sympy_parser.implicit_application(tokens: List[Tuple[int, str]], local_dict: Dict[str, Any], global_dict: Dict[str, Any]) List[Tuple[int, str]][源代码]#

在某些情况下,使括号对于函数调用是可选的。

之后再使用这个 implicit_multiplication() ,否则表达式如下 sin 2x 将被解析为 x * sin(2) 而不是 sin(2*x) .

实例

>>> from sympy.parsing.sympy_parser import (parse_expr,
... standard_transformations, implicit_application)
>>> transformations = standard_transformations + (implicit_application,)
>>> parse_expr('cot z + csc z', transformations=transformations)
cot(z) + csc(z)
sympy.parsing.sympy_parser.function_exponentiation(tokens: List[Tuple[int, str]], local_dict: Dict[str, Any], global_dict: Dict[str, Any])[源代码]#

允许函数指数化,例如。 cos**2(x) .

实例

>>> from sympy.parsing.sympy_parser import (parse_expr,
... standard_transformations, function_exponentiation)
>>> transformations = standard_transformations + (function_exponentiation,)
>>> parse_expr('sin**4(x)', transformations=transformations)
sin(x)**4
sympy.parsing.sympy_parser.implicit_multiplication_application(result: List[Tuple[int, str]], local_dict: Dict[str, Any], global_dict: Dict[str, Any]) List[Tuple[int, str]][源代码]#

允许稍微宽松的语法。

  • 单参数方法调用的括号是可选的。

  • 乘法是隐式的。

  • 符号名称可以拆分(即符号之间不需要空格)。

  • 函数可以是指数的。

实例

>>> from sympy.parsing.sympy_parser import (parse_expr,
... standard_transformations, implicit_multiplication_application)
>>> parse_expr("10sin**2 x**2 + 3xyz + tan theta",
... transformations=(standard_transformations +
... (implicit_multiplication_application,)))
3*x*y*z + 10*sin(x**2)**2 + tan(theta)
sympy.parsing.sympy_parser.rationalize(tokens: List[Tuple[int, str]], local_dict: Dict[str, Any], global_dict: Dict[str, Any])[源代码]#

将浮点数转换为 Rational . 追赶 auto_number .

sympy.parsing.sympy_parser.convert_xor(tokens: List[Tuple[int, str]], local_dict: Dict[str, Any], global_dict: Dict[str, Any])[源代码]#

治疗异或, ^ ,作为指数, ** .

These are included in sympy.parsing.sympy_parser.standard_transformations and generally don't need to be manually added by the user.

sympy.parsing.sympy_parser.lambda_notation(tokens: List[Tuple[int, str]], local_dict: Dict[str, Any], global_dict: Dict[str, Any])[源代码]#

Substitutes "lambda" with its SymPy equivalent Lambda(). However, the conversion does not take place if only "lambda" is passed because that is a syntax error.

sympy.parsing.sympy_parser.auto_symbol(tokens: List[Tuple[int, str]], local_dict: Dict[str, Any], global_dict: Dict[str, Any])[源代码]#

将调用插入 Symbol/Function 对于未定义的变量。

sympy.parsing.sympy_parser.repeated_decimals(tokens: List[Tuple[int, str]], local_dict: Dict[str, Any], global_dict: Dict[str, Any])[源代码]#

允许0.2 [1] 表示重复小数点0.2111的符号。。。(19/90)

在自动编号之前运行这个。

sympy.parsing.sympy_parser.auto_number(tokens: List[Tuple[int, str]], local_dict: Dict[str, Any], global_dict: Dict[str, Any])[源代码]#

将数字字面值转换为使用SymPy等效值。

复数用法 I ,整数字面值使用 Integer ,和浮点字面值使用 Float .

sympy.parsing.sympy_parser.factorial_notation(tokens: List[Tuple[int, str]], local_dict: Dict[str, Any], global_dict: Dict[str, Any])[源代码]#

允许阶乘的标准表示法。

实验 \(\mathrm{{\LaTeX}}\) 句法分析#

The current implementations are experimental. The behavior, parser backend(s) and API might change in the future. Unlike some of the other parsers, \(\mathrm{\LaTeX}\) is designed as a type-setting language, not a computer algebra system and so can contain typographical conventions that might be interpreted multiple ways.

\(\mathrm{{\LaTeX}}\) 解析函数参考#

sympy.parsing.latex.parse_latex(s, strict=False, backend='antlr')[源代码]#

Converts the input LaTeX string s to a SymPy Expr.

参数:

s :结构

要解析的LaTeX字符串。在包含 Latex 的Python源代码中, 原始字符串 (表示为 r" ,比如这个)是首选的,因为 Latex 可以自由地使用 \ 字符,这将触发普通Python字符串中的转义。

backend : str, optional

Currently, there are two backends supported: ANTLR, and Lark. The default setting is to use the ANTLR backend, which can be changed to Lark if preferred.

Use backend="antlr" for the ANTLR-based parser, and backend="lark" for the Lark-based parser.

The backend option is case-sensitive, and must be in all lowercase.

严格的 :bool,可选

This option is only available with the ANTLR backend.

If True, raise an exception if the string cannot be parsed as valid LaTeX. If False, try to recover gracefully from common mistakes.

实例

>>> from sympy.parsing.latex import parse_latex
>>> expr = parse_latex(r"\frac {1 + \sqrt {\a}} {\b}")
>>> expr
(sqrt(a) + 1)/b
>>> expr.evalf(4, subs=dict(a=5, b=2))
1.618
>>> func = parse_latex(r"\int_1^\alpha \dfrac{\mathrm{d}t}{t}", backend="lark")
>>> func.evalf(subs={"alpha": 2})
0.693147180559945

ANTLR Backend#

The ANTLR-based \(\mathrm{\LaTeX}\) parser was ported from latex2sympy. While functional and its API should remain stable, the parsing behavior or backend may change in future releases.

ANTLR \(\mathrm{\LaTeX}\) Parser Caveats#

In its current definition, the parser may fail to fully parse an expression, yet not throw a warning:

parse_latex(r'x -')

will simply find x. What is covered by this behavior will almost certainly change between releases, and become stricter, more relaxed, or some mix.

Lark Backend#

The Lark-based LaTeX parser is newer, and is intended to eventually completely replace the ANTLR-based parser. It has most of the features that the ANTLR-based parser provides, with some extras.

Lark \(\mathrm{\LaTeX}\) Parser Features#

One thing to note is that the Lark backend does not support ill-formed expressions, and it does not try to fix any sort of common mistakes that may have occured. For example, as mentioned in the earlier section, the ANTLR-based parser would simply find x if we run:

parse_latex(r'x -', backend='ANTLR')

However, running:

parse_latex(r'x -', backend='Lark')

will raise an lark.exceptions.UnexpectedEOF exception.

Apart from that, there are a couple of extra things that the Lark-based parser supports that the ANTLR-based parser does not. They are:

  1. Detecting ambiguous expressions, and

  2. Allowing user-customization of the \(\mathrm{\LaTeX}\) grammar at runtime.

Expressions like \(f(x)\) are technically ambiguous \(\mathrm{\LaTeX}\) expressions because the \(f\) might be a function or a variable name. Lark has the capability to point out these ambiguities and notify the user, or even return all possible interpretations.

The Lark-based parser exposes a number of internals which allow the user to customize the parser's behavior. For example, the user can specify their own \(\mathrm{\LaTeX}\) grammar by passing the path to the grammar file to the LarkLaTeXParser while instantiating the parser.

The user can also specify their own custom transformer class to the \(LarkLaTeXParser\) class.

The two examples mentioned above can be found in the test_custom_latex.py file.

Lark \(\mathrm{\LaTeX}\) Parser Capabilities#

In order to use the Lark-based LaTeX parser, it is important to know what it can and cannot do. As the parser is still experimental, it supports many things, but some features are still only partially implemented, or not available.

As such, we will list the types of expressions that it can parse, and then list some expression types of interest where it may fail.

Here is a list of the things which are supported:

  • Symbols which consist of one letter, e.g., a, b, x, etc. Greek symbols and symbols with subscripts are also supported. Numbers are also supported, as is \infty.

  • Symbols with multiple letters are supported, as long as they are wrapped in \mathit.

  • Expressions with \(+\), \(-\), \(*\), \(/\), and alternative operators like \cdot, \times, \div, etc. If two expressions are next to each other, like \(xy\) or \((\sin x)(\cos t)\), then it is treated as implicit multiplication.

  • Relations with \(<\), \(>\), \(\le\), \(\ge\), \(=\), and \(\ne\).

  • Commonly used functions like

    • Square roots,

    • factorials,

    • complex conjugation (like \(\overline{z}\))

    • \(\log\),

    • \(\ln\),

    • \(\exp\),

    • absolute value (e.g., \(|x|\)). Note that \(||x||\) is parsed as Abs(Abs(x)).

    • floor (e.g., \(\lfloor x \rfloor\)) and ceiling (e.g., \(\lceil x \rceil\)),

    • \(\min\) and \(\max\).

  • All the trigonometric functions and their inverses trigonometric functions. Powers like \sin^4 are also supported. The power \(-1\) is interpreted as the inverse function (i.e., \sin^{-1} x is interpreted as \arcsin x).

  • Hyperbolic trigonometric functions (currently only \(\sinh\), \(\cosh\), and \(\tanh\)) and their inverses. As mentioned in the previous point, powers like \tanh^2 are also supported, and \(-1\) is interpreted as the inverse function (i.e., \tanh^{-1} x is interpreted as \arctanh x).

  • AppliedFunctions, like \(f(x, y, z)\).

  • All types of fractions (\frac, \tfrac, \dfrac, \nicefrac) and binomials (\binom, \tbinom, \dbinom) are supported.

  • Integrals, both definite and indefinite. When the integrand is a fraction, having the differential in the numerator is allowed. The differential is allowed to be d, \text{d}, or \mathrm{d}.

  • Derivatives in one variable. I.e., things like \(\dfrac{d}{dx} (\sin x)\). Higher order derivatives and partial derivatives are not supported yet.

  • Limits in one variable. E.g., \(\lim\limits_{t\to 3^{+}} \sin t\).

  • Sums and products with simple conditions. For example, \(\sum\limits_{k=0}^n k^2\) is allowed because the condition on \(k\) is simple. An expression like \(\sum\limits_{d \mid n} d^2\) is not allowed because the condition on \(d\) in the subscript is complicated. Expressions with the index variable specified in the superscript are also allowed. For example, \(\prod\limits_{k=0}^{k=n} k^2\) is parsed correctly.

  • Bra (e.g., \(| x \rangle\)), and Ket (e.g., \(\langle p |\)) notation. Parsing Inner (e.g., \(\langle x | y \rangle\)) and Outer Products (e.g., \(| y \rangle \langle x |\)) is also supported.

Here is a(n incomplete) list of things which are currently not supported, which may be added in the future:

  • Matrices. Stuff like \begin{env}...\end{env}, where env is any of matrix, bmatrix, pmatrix, smallmatrix, and array.

  • Matrix operations like matrix-matrix addition, scalar-matrix multiplication, matrix-matrix multiplication.

  • Higher order derivatives and partial derivatives.

  • Double and triple integrals.

Lark \(\mathrm{\LaTeX}\) Parser Functions#

sympy.parsing.latex.parse_latex_lark(s: str)[源代码]#

Experimental LaTeX parser using Lark.

This function is still under development and its API may change with the next releases of SymPy.

Lark \(\mathrm{\LaTeX}\) Parser Classes#

class sympy.parsing.latex.lark.LarkLaTeXParser(print_debug_output=False, transform=True, grammar_file=None, transformer=None)[源代码]#

Class for converting input \(\mathrm{\LaTeX}\) strings into SymPy Expressions. It holds all the necessary internal data for doing so, and exposes hooks for customizing its behavior.

参数:

print_debug_output : bool, optional

If set to True, prints debug output to the logger. Defaults to False.

transform : bool, optional

If set to True, the class runs the Transformer class on the parse tree generated by running Lark.parse on the input string. Defaults to True.

Setting it to False can help with debugging the \(\mathrm{\LaTeX}\) grammar.

grammar_file : str, optional

The path to the grammar file that the parser should use. If set to None, it uses the default grammar, which is in grammar/latex.lark, relative to the sympy/parsing/latex/lark/ directory.

transformer : str, optional

The name of the Transformer class to use. If set to None, it uses the default transformer class, which is TransformToSymPyExpr().

class sympy.parsing.latex.lark.TransformToSymPyExpr[源代码]#

Returns a SymPy expression that is generated by traversing the lark.Tree passed to the .transform() function.

参数:

visit_tokens : bool, optional

For information about what this option does, see here.

Note that the option must be set to True for the default parser to work.

笔记

This class is never supposed to be used directly.

In order to tweak the behavior of this class, it has to be subclassed and then after the required modifications are made, the name of the new class should be passed to the LarkLaTeXParser class by using the transformer argument in the constructor.

\(\mathrm{{\LaTeX}}\) 分析异常引用#

class sympy.parsing.latex.LaTeXParsingError[源代码]#

SymPy表达式引用#

class sympy.parsing.sym_expr.SymPyExpression(source_code=None, mode=None)[源代码]#

类来存储和处理SymPy表达式

这个类将保存SymPy表达式并处理用于与不同语言的转换的API。

它与C语言和Fortran解析器一起生成SymPy表达式,这些表达式存储在这里,可以转换成多种语言的源代码。

笔记

该模块及其API目前正在开发和试验阶段,可以在开发过程中进行更改。

Fortran解析器不支持数值赋值,因此所有变量都已初始化为零。

该模块还依赖于外部依赖关系:

  • 使用Fortran解析器所需的LFortran

  • C解析器所需的Clang

实例

解析C代码的示例:

>>> from sympy.parsing.sym_expr import SymPyExpression
>>> src = '''
... int a,b;
... float c = 2, d =4;
... '''
>>> a = SymPyExpression(src, 'c')
>>> a.return_expr()
[Declaration(Variable(a, type=intc)),
Declaration(Variable(b, type=intc)),
Declaration(Variable(c, type=float32, value=2.0)),
Declaration(Variable(d, type=float32, value=4.0))]

An example of variable definition:

>>> from sympy.parsing.sym_expr import SymPyExpression
>>> src2 = '''
... integer :: a, b, c, d
... real :: p, q, r, s
... '''
>>> p = SymPyExpression()
>>> p.convert_to_expr(src2, 'f')
>>> p.convert_to_c()
['int a = 0', 'int b = 0', 'int c = 0', 'int d = 0', 'double p = 0.0', 'double q = 0.0', 'double r = 0.0', 'double s = 0.0']

赋值示例:

>>> from sympy.parsing.sym_expr import SymPyExpression
>>> src3 = '''
... integer :: a, b, c, d, e
... d = a + b - c
... e = b * d + c * e / a
... '''
>>> p = SymPyExpression(src3, 'f')
>>> p.convert_to_python()
['a = 0', 'b = 0', 'c = 0', 'd = 0', 'e = 0', 'd = a + b - c', 'e = b*d + c*e/a']

函数定义示例:

>>> from sympy.parsing.sym_expr import SymPyExpression
>>> src = '''
... integer function f(a,b)
... integer, intent(in) :: a, b
... integer :: r
... end function
... '''
>>> a = SymPyExpression(src, 'f')
>>> a.convert_to_python()
['def f(a, b):\n   f = 0\n    r = 0\n    return f']
convert_to_c()[源代码]#

Returns a list with the c source code for the SymPy expressions

实例

>>> from sympy.parsing.sym_expr import SymPyExpression
>>> src2 = '''
... integer :: a, b, c, d
... real :: p, q, r, s
... c = a/b
... d = c/a
... s = p/q
... r = q/p
... '''
>>> p = SymPyExpression()
>>> p.convert_to_expr(src2, 'f')
>>> p.convert_to_c()
['int a = 0', 'int b = 0', 'int c = 0', 'int d = 0', 'double p = 0.0', 'double q = 0.0', 'double r = 0.0', 'double s = 0.0', 'c = a/b;', 'd = c/a;', 's = p/q;', 'r = q/p;']
convert_to_expr(src_code, mode)[源代码]#

Converts the given source code to SymPy Expressions

实例

>>> from sympy.parsing.sym_expr import SymPyExpression
>>> src3 = '''
... integer function f(a,b) result(r)
... integer, intent(in) :: a, b
... integer :: x
... r = a + b -x
... end function
... '''
>>> p = SymPyExpression()
>>> p.convert_to_expr(src3, 'f')
>>> p.return_expr()
[FunctionDefinition(integer, name=f, parameters=(Variable(a), Variable(b)), body=CodeBlock(
Declaration(Variable(r, type=integer, value=0)),
Declaration(Variable(x, type=integer, value=0)),
Assignment(Variable(r), a + b - x),
Return(Variable(r))
))]

属性

src_code

(字符串)要转换的源代码或源代码的文件名

模式:字符串

根据C/C++语言的FORTRAN C或C语言,根据源代码F或F语言确定使用哪个解析器的模式

convert_to_fortran()[源代码]#

Returns a list with the fortran source code for the SymPy expressions

实例

>>> from sympy.parsing.sym_expr import SymPyExpression
>>> src2 = '''
... integer :: a, b, c, d
... real :: p, q, r, s
... c = a/b
... d = c/a
... s = p/q
... r = q/p
... '''
>>> p = SymPyExpression(src2, 'f')
>>> p.convert_to_fortran()
['      integer*4 a', '      integer*4 b', '      integer*4 c', '      integer*4 d', '      real*8 p', '      real*8 q', '      real*8 r', '      real*8 s', '      c = a/b', '      d = c/a', '      s = p/q', '      r = q/p']
convert_to_python()[源代码]#

Returns a list with Python code for the SymPy expressions

实例

>>> from sympy.parsing.sym_expr import SymPyExpression
>>> src2 = '''
... integer :: a, b, c, d
... real :: p, q, r, s
... c = a/b
... d = c/a
... s = p/q
... r = q/p
... '''
>>> p = SymPyExpression(src2, 'f')
>>> p.convert_to_python()
['a = 0', 'b = 0', 'c = 0', 'd = 0', 'p = 0.0', 'q = 0.0', 'r = 0.0', 's = 0.0', 'c = a/b', 'd = c/a', 's = p/q', 'r = q/p']
return_expr()[源代码]#

返回表达式列表

实例

>>> from sympy.parsing.sym_expr import SymPyExpression
>>> src3 = '''
... integer function f(a,b)
... integer, intent(in) :: a, b
... integer :: r
... r = a+b
... f = r
... end function
... '''
>>> p = SymPyExpression()
>>> p.convert_to_expr(src3, 'f')
>>> p.return_expr()
[FunctionDefinition(integer, name=f, parameters=(Variable(a), Variable(b)), body=CodeBlock(
Declaration(Variable(f, type=integer, value=0)),
Declaration(Variable(r, type=integer, value=0)),
Assignment(Variable(f), Variable(r)),
Return(Variable(f))
))]

运行时安装#

The currently-packaged LaTeX parser backend is partially generated with ANTLR4, but to use the parser, you only need the antlr4 Python package available.

Depending on your package manager, you can install the right package with, for example, pip:

$ pip install antlr4-python3-runtime==4.11

or conda:

$ conda install -c conda-forge antlr-python-runtime==4.11

C解析器依赖于 clang Fortran解析器依赖于 LFortran . 您可以使用以下命令安装这些程序包:

$ conda install -c conda-forge lfortran clang