dongre1907 2013-06-16 17:01
浏览 33
已采纳

将一个字符串附加到另一个字符串,但附加物位于新行而不是同一行

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
  • 写回答

1条回答 默认 最新

  • duanbo5230 2013-06-16 17:04
    关注

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

    foreach ($lines as $line) {
        if ($line[strlen($line)-1] == "
    ")
            $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."
    ");
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题