I have ~150 student-submitted Mathematica notebooks for an assessed assignment. While I've been marking them, I'm suspecting there is a reasonable amount of plagiarism going on, when multiple students make the same odd errors throughout.
When I find something odd, I can use Notebook++ to search through all the notebooks for where it crops up elsewhere, but the .nb files have a lot of extra RowBox
and BoxData
etc.
I'm looking to convert just the input cells from each notebook into a text file, is there a way to do that programmatically?
The answer at: Converting a notebook to plain text programmatically shows how to automate the process of saving a single notebook as a text file, but I want just the "Input"
Cell
s and can't figure out how to do that.
Edit:
The answer from Alexey works generally, except when an integral has been input using the Integral sign on the palette. Running the code:
name = "test2.nb"
Export["test.txt", StringJoin[
Riffle[NotebookImport[name, "Input" -> "Text"],
"\n=================\n"]], "Text", CharacterEncoding -> "PrintableASCII"]
then makes something strange happen involving a SubsuperscriptBox
that I can't fix, which makes the output go over two columns, but within the text file:
Answer
Updated to support multiline input cells and syntax errors
I would avoid linear syntax. Why not use something like the following:
inputCellsToText[nb_, textFile_] := Internal`InheritedBlock[
{SequenceForm},
SetAttributes[SequenceForm, HoldAll];
Export[
textFile,
Flatten[extractInput /@ NotebookImport[nb, "Input"->"HeldInterpretedCell"]],
"Text"
]
]
extractInput[HoldComplete[ExpressionCell[a_List, __]]] := DeleteCases[
SequenceForm /@ Unevaluated[a],
SequenceForm[Null]
]
extractInput[HoldComplete[ExpressionCell[a_, __]]] := SequenceForm[a]
For example, the following notebook:
nb = Uncompress @"1:eJzVVc1rE0EUj7WxftBaD4onWQ9KQmrNbkIa24gkaSJVYyRbVMTLJp1tR9OZMDtrGw/iWfQqFRT8I6SXinryIChexVJQ60F6Kd48CM6bbD42TfMh9eDlzb437/P33rw9nqc50+vxeKy9glymHOUpvW3uBkm/IJewxc1dVS6JikWzD7hBhzvPqF2aNLjRZNLvMpEOBgRJ0EWp7N3qf48gObogNCoRarfS8SFBdDtv2SXErALDJS4UdbC5Oa5pWkIHH8GaQE11cCq5A4KkmVHgmBJwBybqFkNXYVLH14WOKmmgEmhIZu9KHW4rVJPU3z5hp7L0WDjpmDqCUDzURTaVGAHnu42pG6XOjsOSKg3fAR2aO0VKNq97y9lFZB10xiE5Z5BZNI3nkVWfE/CIwB5s7iRuodWljfijh5/n4KxdrCwPvVoXgsfvIq/hZM+9A2/XGzU+Dg++B8Fmjn6AsymHw+IjNV+aMyx8F+llwo3FFGOUWVJlmtmoXmTr0W05ORVEg6FksAHirM27AkHmDgrjR3/Lct/E78vqTi+dkLVMfJk4+x1qaZ+a04QdDR0bj8nQ0ku2hEh3y6DFC94e0TYPvPmVhHoZLgQa1bn4ufltBQp80Bd+udoZy96S6gXyOoCADVuO3ZD5/EuA2z7jbTdUdaYTauMK2aH1mK+t6mBUCgqVLfjX/c18+vFkTeC4ce/rs7Uu+vs/YdLTi24E5djJF08BjCNXfklQ6kPm9rNffFzDZIYu6GItuodrChKNBqPyjETPNJkO1kwzBpvFxGr1o61yOCYys/YJLm5zOm9wXHAruO+wJrgWJacZJTxFZq6K1ogFrJ8TMlUdVRWTMiVjFJSsrlxXFqMRxRfSTuUxH1EiYTiVi4gRVPQrvgsGsQ1WVsIjihZUx/xNUYah9bxcRJPIxATDmrd0QEnwhl3koyT/ByPIIdA=";
produces the following text file:
Integrate[1/(1 + x^2), {x, 0, Infinity}]
2 + 2
ErrorBox[ErrorBox[RowBox[{RowBox[{"4", " ", "4"}], "+"}]]]
Subscript[x, 2]^3
α^2 + (Element[b, c])
Comments
Post a Comment