本文介绍了在python中显示sympy渲染svg时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在程序退出之前实际上不会产生svg,因此显然无法显示.
是否有一种提高性能的方法(不是每次都查找'svgmath.xml'?)
是否需要生成实际的svg文件? svgmath可以将输出直接传递到QSvgWidget吗?
我有以下程序,该程序使用sympy和svgmath来呈现用户的代数表达式.几乎可以使用,但是存在一些问题:
I have the following program which uses sympy and svgmath to render a user's algebraic expression. It nearly works but there are a few issues:
非常感谢和最良好的祝愿.
Many thanks and best wishes.
from __future__ import division import sys import sympy from PySide.QtGui import * from PySide.QtCore import * from PySide.QtXml import * from PySide.QtSvg import * from xml import sax from xml.sax.saxutils import XMLGenerator from svgmath.tools.saxtools import XMLGenerator, ContentFilter from svgmath.mathhandler import MathHandler, MathNS from sympy.printing.mathml import mathml from sympy.abc import x from sympy.utilities.mathml import c2p import libxml2 import StringIO class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) self.browser = QTextBrowser() self.browser.setCurrentFont(QFont("Courier New",10,QFont.Bold)) self.lineedit = QLineEdit("please type an expression") self.lineedit.selectAll() self.svgwidget = QSvgWidget() layout = QVBoxLayout() layout.addWidget(self.browser) layout.addWidget(self.lineedit) layout.addWidget(self.svgwidget) self.setLayout(layout) self.lineedit.setFocus() self.connect(self.lineedit, SIGNAL("textChanged (const QString&)"),self.updateUi) def updateUi(self): text = unicode(self.lineedit.text()) for z in range(0,9): text = text.replace('x'+str(z),'x^'+str(z)) text = text.replace(')'+str(z),')^'+str(z)) text = text.replace(str(z)+'x',str(z)+'*x') text = text.replace(str(z)+'(',str(z)+'*(') try: prettytext = sympy.printing.pretty(sympy.sympify(text)) self.browser.clear() self.browser.append(prettytext) # Open all files output = open("test.svg", "w") config = open("svgmath.xml", "r") # Create the converter as a content handler. saxoutput = XMLGenerator(output, 'utf-8') handler = MathHandler(saxoutput, config) # Parse input file with a namespace-aware SAX parser parser = sax.make_parser() parser.setFeature(sax.handler.feature_namespaces, 1) parser.setContentHandler(handler) parser.parse(StringIO.StringIO(c2p(mathml(sympy.sympify(text)), simple=True))) self.svgwidget.load("test.svg") except Exception: if text=='': self.browser.clear() app = QApplication(sys.argv) form = Form() form.show() app.exec_()推荐答案
您应该关闭文件句柄,因为否则写入的数据可能尚未刷新到文件系统中.
You should close the file handles, because otherwise the data written may not yet have been flushed to the filesystem.
parser.parse() output.close()或者,使用with表达式.
with open("test.svg", "w") as output: ... parser.parse() load()
是否需要生成实际的svg文件?
Does an actual svg file need to be produced?
我认为QSvgWidget提供了一个load插槽,该插槽需要包含文件内容的字节字符串.
I think QSvgWidget offers a load slot, which takes a byte string with the file contents.
更多推荐
在python中显示sympy渲染svg时出现问题
发布评论