跳转到主要内容

Mathematica解析器和翻译器

项目描述

https://travis-ci.org/rocky/FoxySheep2.svg?branch=master

这是Robert Jacobson用Python实现的FoxySheep解析器和词法分析器,针对Mathematica。它已经进行了精简和重组。

示例

安装后,命令行翻译器命名为foxy-sheep,可以将Mathematica InputForm转换为Mathematica FullForm,无需安装Mathematica:要交互式运行代码

$ foxy-sheep
Enter a Mathematica expression. Enter either an empty line, Ctrl-C, or Ctrl-D to exit.
In[1]:= 1+2
Plus[1,2]
In[1]:=D[4 x^2]
D[Times[4,Power[x,2]]]
In[1]:=
$

来自数学学生快速入门的前几个示例

foxy-sheep -o python
Enter a Mathematica expression. Enter either an empty line, Ctrl-C, or Ctrl-D to exit.
In[1]:= 2 + 2
(2 + 2)

Out[1]=4
In[2]:= 1 + 2 + 3
(1 + 2 + 3)

Out[2]=6
In[3]:= % + 4
(Out() + 4)

Out[3]=10
In[4]:= 5 + 2 * 3 - 7.5
(5 + 2 * 3 -
decimal.Decimal(7.5))

In[5]:= ((5 - 3) ^ (1 + 2))/ 4
((5 - 3) ** (1 + 2) / 4)

Out[5]=2.0
In[6]:= GCD[12,15]
math.gcd(12, 15)

Out[6]=3
In[7]:= {1, 2, 3}
[1, 2, 3]

Out[7]=[1, 2, 3]

从Python调用

from FoxySheep import if2ff, if2python
print(if2ff("x^2-3x+4")
# Prints: Plus[Power[x,2],Times[-1,3,x],4]
print(if2ff("x^2-3x+4")
# Prints (x ** 2 + -1 * 3)

要运行更多演示,请运行foxy-sheep --file pytest/parse_expressions/SO1.m 或其他Mathamatica文件在pytest/parse_expressions中。

要获取关于foxy-sheep的帮助,请运行foxy-sheep --help

转换为Python

已经开始了一个非常粗略的Python转换器。虽然还有很多细节需要完善,但一些基本功能已经具备。

以下是一些示例

167.5 -> decimal.Decimal(167.5)
15^^8 -> int(15, 8)
132`  -> (132)
1 / 10 3 -> (1 / 10 * 3)
x^2 + y^2 -> (x ** 2 + y ** 2)
GCD[12, 15] -> math.gcd(12, 15)
Range[10] -> range(10)
{a, b, c, d}[[3]] -> [a, b, c, d][2]  # Handles 0-1 conversion
{a, b, c, d, e, f}[[2 ;; 4]] -> [a, b, c, d, e, f][1:3] # ditto

将转换到Python是通过将“InputForm”输入转换为“OutputForm”解析树,然后使用它来转换为Python AST,最后使用Python模块astor将其转换为文本。

为什么我们要通过这种更复杂的方式将一个字符串转换为另一个字符串?

通过保持结构为AST,我们可以考虑更强大的转换,并利用用于处理Python AST的现有程序。

例如,将 {1,2,3} + 2 翻译成 Python,虽然目前尚未处理,但可以通过查看加法操作符的操作数的类型来实现,注意一个是标量而另一个是列表。

重新生成词法分析器/解析器

要更改语法,您需要安装 ANTLR 解析器生成器(antlr4),版本 4.7.x。

要(重新)生成词法分析器/解析器,您需要

$ make

生成的文件放置在 FoxySheep/generated 目录中。

ANTLR4 生成的文件假定位于名为 generated 的子目录中,其中包含一个空的 __init__.py 文件。有关详细信息,请参阅 Makefile。

FoxySheepLexer 必须继承自 Lexer

为了使生成的 antlr4 词法分析器正常工作,我们需要修复生成的 Python 词法分析器 FoxySheep.lexer.py;修复文件 FoxySheep.lexer.py.patch 执行此操作。对于 FoxySheepParser.py 的 Makefile 目标包含 patch 命令。

如果未执行修复,则在尝试运行它(例如通过 foxy-sheep)时,您将在词法分析器中遇到 AttributeError 异常。

AttributeError: 'FoxySheepLexer' object has no attribute 'checkAdditiveOp'

另请参阅

FoxySheep

项目详情


下载文件

下载适用于您平台的应用程序文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分发

FoxySheep-1.2.3.tar.gz (108.6 kB 查看散列)

上传时间

构建分发

FoxySheep-1.2.3-py38-none-any.whl (121.5 kB 查看散列)

上传时间 Python 3.8

FoxySheep-1.2.3-py36-none-any.whl (121.5 kB 查看散列)

上传时间 Python 3.6

FoxySheep-1.2.3-py3.8.egg (277.6 kB 查看散列)

上传时间

FoxySheep-1.2.3-py3.7.egg (277.1 kB 查看散列)

上传时间

FoxySheep-1.2.3-py3.6.egg (277.2 kB 查看散列)

上传时间