0
votes

I am an R users who is beginning to work in Python. I am trying o use knitr to knit a Python file and capture a tree diagram but it is not working. Here is the .Rnw (Latex based) file I am trying to knit:

\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}

But all that is returned is:

enter image description here

It appears that nktl can't be found but I run it in spyder just fine and plot the tree diagram. What do I need to do to include this diagram in the Rnw file for output to a pdf? The x.split error indicates Python is found but I'm not importing correctly in knitr.

I am using Python 3.4.3 64 bit for Windows 7.

1
You last chunk should have engine='python'Dason
And it works on my machine. I'm guessing it's an issue with where your nltk is installed.Dason
Thanks Dason. I'll keep playing.Tyler Rinker
Dason I found I had two version of Python. I fixed my Path variable and it runs without the ImportError but the tree diagram doesn't plot. DId it plot for you?Tyler Rinker

1 Answers

0
votes

Not sure if knitr does Python graphics per: knitr: python engine output not in .md or .html

If not here's the way to solve this:

\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}