JayGatz
JayGatz

Reputation: 271

Appending one string to another, but appendage is on new line not same line

I am appending something to each line in a file and then writing that to a new file.

But when I looked at the new file what it is doing is writing the line from the old file then writing what it should be appending to that line on a new line.

So if the first line in the old file is

A

The first and second line in the new file is

A
/appendage

What it should be is one line:

A /appendage

How can I fix my code so that the appendages are on the same line as what they are being appended to?

function writeTag($tags, $line, $file){
    foreach($tags as $t){
        $line .= " /".$t['tag']." ";
        fwrite($file, $line);
    }
}
$tagger = new PosTagger('lexicon.txt');
$lines = file('dictionary.txt');
$out = fopen("tagged.txt", "w");
foreach($lines as $line){
    $tags = $tagger->tag($line);
    writeTag($tags, $line, $out);
}

Update:

With bwoebi's updated answer adding IGNORE_NEW_LINES, the output file I am getting looks like:

A /DT A$ /DT A&E /DT A&E /DT  /NN A&M /DT A&M /DT  /NN
A&P /DT A&P /DT  /NN

What I am looking for is:

A /DT
A$ /DT
A&E /DT
A&E /DT /NN
A&M /DT
A&M /DT /NN
A&P /DT
A&P /DT /NN

Upvotes: 0

Views: 113

Answers (1)

bwoebi
bwoebi

Reputation: 23787

file() returns the strings until the newline (\n) inclusive: so cut it off when there's one \n as the last character of the string.

foreach ($lines as $line) {
    if ($line[strlen($line)-1] == "\n")
        $line = substr($line, 0, -1);
    $tags = $tagger->tag($line);
    writeTag($tags, $line, $out);
}

Update: Better method: use FILE_IGNORE_NEW_LINES. This constant prevents that the newlines are added.

$lines = file('dictionary.txt', FILE_IGNORE_NEW_LINES);

Answer to updated question: append a newline each time you have finished with one $tag:

function writeTag($tags, $line, $file){
    foreach($tags as $t){
        $line .= " /".$t['tag']." ";
        fwrite($file, $line."\n");
    }
}

Upvotes: 1

Related Questions