knitr + python情节树图

时间:2015-09-13 01:53:57

标签: python python-3.x knitr

我是一名开始使用Python的R用户。我正在尝试使用knitr编织Python文件并捕获树形图但它无法正常工作。这是我试图编织的.Rnw(基于Latex的)文件:

\documentclass{article}
\begin{document}

Hello world!

<<r test-python1, engine='python'>>=
x = 'hello, python world!'
print(x)
@

<<r test-python2, engine='python', echo=FALSE>>=
import nltk
from nltk.tree import *
from nltk.draw import tree

grammar = r"""
    NP:
    {<.*>+}          # Chunk everything
    }<VBD|IN>+{      # Chink sequences of VBD and IN
  """
sentence = [("the", "DT"), ("little", "JJ"), ("yellow", "JJ"),
       ("dog", "NN"), ("barked", "VBD"), ("at", "IN"),  ("the", "DT"), ("cat", "NN")]
cp = nltk.RegexpParser(grammar)
result = cp.parse(sentence)
result
@

<<python>>=
x = 'hello, python world!'
print(x.split(' '))
@

\end{document}
\end{document}

但所有返回的是:

enter image description here

看来nktl无法找到,但我在spyder中运行它很好并绘制了树形图。如何将此图表包含在Rnw文件中以输出到pdf,我需要做什么? x.split错误表示找到了Python,但我没有在knitr中正确导入。

我在Windows 7中使用Python 3.4.3 64位。

1 个答案:

答案 0 :(得分:0)

不确定knitr是否按照knitr: python engine output not in .md or .html

执行Python图形

如果不是,那么解决这个问题的方法是:

\documentclass{article}

\begin{document}

Hello world!

<<r test-python1, engine='python'>>=
x = 'hello, python world!'
print(x)
@


<<r test-python2, engine='python', echo=FALSE>>=
import nltk
from nltk import Tree
from nltk.draw.util import CanvasFrame
from nltk.draw import TreeWidget

dp1 = Tree('dp', [Tree('d', ['the']), Tree('np', ['dog'])])
dp2 = Tree('dp', [Tree('d', ['the']), Tree('np', ['cat'])])
vp = Tree('vp', [Tree('v', ['chased']), dp2])
vp = Tree('vp', [Tree('v', ['chased']), dp2])
sentence = Tree('s', [dp1, vp])

cf = CanvasFrame()

tc = TreeWidget(cf.canvas(),sentence)
cf.add_widget(tc,10,10) # (10,10) offsets
cf.print_to_file('cache/tree.ps')
cf.destroy()

@


<<r r-code>>=
fls <- file.path(getwd(), c('cache/tree.ps',  'cache/tree.png'))
system(sprintf('"C:/Program Files/ImageMagick-6.9.0-Q16/convert.exe" %s %s', fls[1], fls[2]))
@


\begin{figure}[!ht]
  \centering
    \includegraphics[scale=.71]{cache/tree.png}
  \caption{yay!}  \label{regexviz}}  
\end{figure}

<<r test-python3, engine='python'>>=
x = 'hello, python world!'
print(x.split(' '))
@


\end{document}

\end{document}