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."
    ");
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等