|
Blog
|
|
|
|
|
Latex Table Formatting Script
Posted
Tuesday, June 11th 2013 in
Other Tech -
Permalink
Here is a nice, simple script that turns a newline-delimited text file of items into a Latex-format table. The script accepts four parameters. The first parameter is the file to read from. The second parameter is the file to write to. The third parameter is a integer specifying the number of columns to divide the data into. The fourth parameter is optional, and specifies whether to wrap the items in a typewriter tag.
An example of calling the script:
% ./columnize.php infile.txt outfile.txt 3 y
The script:
#!/usr/local/bin/php
<?php
// Reads a file, and columnizes it for Latex tables.
// Parameters:
// 1 - the file to read from
// 2 - the file to write to
// 3 - the number of columns to create
// 4 - wrap text in \texttt{} (y,n) [optional]
$readfilename = $argv[1];
$writefilename = $argv[2];
$columns = $argv[3];
$typewrite = $argv[4];
$readfile = fopen($readfilename, 'r');
$writefile = fopen($writefilename, 'w');
echo "Loading from " . $readfilename . " and writing output to " . $writefilename . "\n";
if(!$readfile)
{
echo "Unable to open file " . $readfilename . " to read";
die;
}
if(!$writefile)
{
echo "Unable to open file " . $writefilename . " to write";
die;
}
$i = 1;
$rows = 0;
$pending = "";
while (!feof($readfile))
{
if($typewrite == "y")
$pending .= " \\texttt{" . str_replace("\n", "", fgets($readfile)) . "} ";
else
$pending .= str_replace("\n", "", fgets($readfile));
if($i % $columns == 0)
{
$pending .= " \\\\";
fwrite($writefile, $pending . "\n");
$pending = "";
$rows++;
}
else
$pending .= " & ";
$i++;
}
if($pending != "")
{
fwrite($writefile, $pending . "\n");
$rows++;
}
echo "Formatted " . $i . " items into " . $rows . " rows.\n";
fclose($readfile);
fclose($writefile);
?>
|
|
|