【问题标题】:split lines/sentence with over 10 words where the first comma appears在第一个逗号出现的地方分割超过 10 个单词的行/句子
【发布时间】:2019-10-04 16:51:25
【问题描述】:

我有以下代码,每 10 个单词分割一行。

    #!/bin/bash

while read line
do
counter=1;
    for word in $line
    do
        echo -n $word" ";
    if (($counter % 10 == 0))
      then
        echo "";
    fi
    let counter=counter+1;
    done
done < input.txt

问题是分割点是第10个词。相反,我希望分割点成为第一个逗号字符(仅适用于超过 10 个单词的句子)。

示例:

line1:来自测试行的短语,我想将其拆分,但我不知道如何拆分。

到

line1:来自测试行的短语, line2:我想拆分,不知道怎么拆分。

如果没有找到逗号,则直接返回该行。

谢谢!

编辑:可以使用 Python 或 Bash 解决方案。

【问题讨论】:

  • 您在寻找 python 解决方案还是 bash 解决方案?
  • 我已经删除了 Python 标记,直到您返回有关该标记在此处的相关性或 Python 解决方案是否可以接受的答案。
  • 其实bash或者python方案都可以。

标签: python bash text split


【解决方案1】:

更好的方法是使用 awk 并测试 15 个或更多单词,如果是,只需将 ",\n" 替换为 ", ",例如

awk 'NF >= 15 {sub (", ", ",\n")}1' file

使用/输出示例

使用您在file 中的输入,您将拥有:

$ awk 'NF >= 15 {sub (", ", ",\n")}1' file
phrase from a test line,
which I want to split, and I don't know how.

(如果您有大量行,awk 将比 shell 循环快几个数量级)

【讨论】:

    【解决方案2】:

    我不确定您是要拆分10 字还是15 字。

    如果您正在处理15 字词,只需将10 替换为15。

    awk -v OFS=, 'NF > 10{ sub(/, */, ",\n", $0); print }' input.txt
    

    或更清楚:

    #! /bin/bash
    
    awk -v OFS=, 'NF > 10{
    
        # enter this block iff words > 10
    
        # replace first occurence of , and additional space,
        # if any, with newline
        sub(/, */, ",\n", $0)
        print
    
    }' input.txt
    

    【讨论】:

    • 10/15 足够接近,标题和文字让人有点困惑。英雄所见略同。我认为我们的答案相隔不到 5 秒。
    • @DavidC.Rankin,哈哈,是的,看到你的答案后我也想知道同样的问题,虽然公平地说,你的答案更精确,更短,被赞成。
    • 两者都值得紫外线。
    【解决方案3】:

    这是一个检查字符串中单词数量的简单解决方案。如果字符串中的单词数超过 10 则将拆分:

    output = []
    s = 'phrase from a test line, which I want to split, and I dont know how'
    while len (s.split()) > 10:
        first_sent,s = s.split(',',1)
        output.append(first_sent)
    output.append(s)
    

    【讨论】:

      【解决方案4】:

      这是问题for loop in bash simply prints n times the command instead of reiterating的简单版本

      简单的版本可以处理

      # For each line with 10 words append a newline after the first comma
      sed -r '/((\w)+ ){10}/s/,/,\n/' input.txt
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-06
        • 1970-01-01
        • 2022-11-03
        • 1970-01-01
        • 2021-03-27
        • 1970-01-01
        • 2019-01-24
        • 1970-01-01
        相关资源
        最近更新 更多