代码之家  ›  专栏  ›  技术社区  ›  Alex Angas Colin

代码高尔夫7月4日版:统计前十个发生的单词

  •  11
  • Alex Angas Colin  · 技术社区  · 5 年前

    考虑到下面列出的总统在最小的程序中做了前十个单词的计数:

    输入文件

        Washington
        Washington
        Adams
        Jefferson
        Jefferson
        Madison
        Madison
        Monroe
        Monroe
        John Quincy Adams
        Jackson
        Jackson
        Van Buren
        Harrison 
        DIES
        Tyler
        Polk
        Taylor 
        DIES
        Fillmore
        Pierce
        Buchanan
        Lincoln
        Lincoln 
        DIES
        Johnson
        Grant
        Grant
        Hayes
        Garfield 
        DIES
        Arthur
        Cleveland
        Harrison
        Cleveland
        McKinley
        McKinley
        DIES
        Teddy Roosevelt
        Teddy Roosevelt
        Taft
        Wilson
        Wilson
        Harding
        Coolidge
        Hoover
        FDR
        FDR
        FDR
        FDR
        Dies
        Truman
        Truman
        Eisenhower
        Eisenhower
        Kennedy 
        DIES
        Johnson
        Johnson
        Nixon
        Nixon 
        ABDICATES
        Ford
        Carter
        Reagan
        Reagan
        Bush
        Clinton
        Clinton
        Bush
        Bush
        Obama
    

    在…开始 猛击97 文字

    cat input.txt | tr " " "\n" | tr -d "\t " | sed 's/^$//g' | sort | uniq -c | sort -n | tail -n 10
    

    产量 :

          2 Nixon
          2 Reagan
          2 Roosevelt
          2 Truman
          2 Washington
          2 Wilson
          3 Bush
          3 Johnson
          4 FDR
          7 DIES
    

    在你认为合适的时候断开领带!快乐第四!

    对于你们这些关心总统的人,可以找到更多的信息 here .

    17 回复  |  直到 9 年前
        1
  •  11
  •   Stig Brautaset    15 年前

    较短的shell版本:

    xargs -n1 < input.txt | sort | uniq -c | sort -nr | head
    

    如果你想要不区分大小写的排名,改变 uniq -c 进入之内 uniq -ci .

    稍微短一点,如果你对排名被颠倒和可读性因缺乏空格而受损感到高兴的话。此时钟为46个字符:

    xargs -n1<input.txt|sort|uniq -c|sort -n|tail
    

    (如果允许您首先将输入文件重命名为“i”,则可以将此值减少到38。)

    注意到,在这种特殊情况下,没有任何单词出现超过9次,我们可以通过从最后一类中删除“-n”参数来删除3个字符:

    xargs -n1<input.txt|sort|uniq -c|sort|tail
    

    这样就可以在不重命名输入文件的情况下将此解决方案减少到43个字符。(或者35岁,如果你愿意的话。)

    使用 xargs -n1 在每行将文件拆分为一个单词比 tr \ \\n 解决方案,因为这会创建许多空白行。这意味着解决方案不正确,因为它遗漏了尼克松,显示了一个空字符串,显示256次。但是,空字符串不是“单词”。

        2
  •  12
  •   Simon Steele    15 年前

    C,153:

    在以下位置读取文件 p 并将结果打印到控制台:

    File.ReadLines(p)
        .SelectMany(s=>s.Split(' '))
        .GroupBy(w=>w)
        .OrderBy(g=>-g.Count())
        .Take(10)
        .ToList()
        .ForEach(g=>Console.WriteLine(g.Count()+"|"+g.Key));
    

    如果只生成列表而不打印到控制台,那么它是93个字符。

    6|DIES
    4|FDR
    3|Johnson
    3|Bush
    2|Washington
    2|Adams
    2|Jefferson
    2|Madison
    2|Monroe
    2|Jackson
    
        3
  •  7
  •   ojblass    15 年前

    VIM 60

        :1,$!tr " " "\n"|tr -d "\t "|sort|uniq -c|sort -n|tail -n 10
    
        4
  •  7
  •   Jason Watts    15 年前

    VIM 36

    :%s/\W/\r/g|%!sort|uniq -c|sort|tail
        5
  •  5
  •   fooledbyprimes    15 年前

    哈斯克尔,102个字符(哇,非常接近于原版):

    import List
    (take 10.map snd.sort.map(\(x:y)->(-length y,x)).group.sort.words)`fmap`readFile"input.txt"
    

    J ,仅55个字符:

    10{.\:~~.(,.~[:<"0@(+/)=/~);;:&.><;._2[1!:1<'input.txt'
    

    (我还没有弄清楚如何在J中优雅地执行文本操作……它在阵列结构数据方面要好得多。)


       NB. read the file
       <1!:1<'input.txt'
    +---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------...
    |    Washington     Washington     Adams     Jefferson     Jefferson     Madison     Madison     Monroe     Monroe     John Quincy Adams     Jackson     Jackson     Van Buren     Harrison DIES     Tyler     Polk     Taylor DIES     Fillmore     Pierce     ...
    +---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------...
       NB. split into lines
       <;._2[1!:1<'input.txt'
    +--------------+--------------+---------+-------------+-------------+-----------+-----------+----------+----------+---------------------+-----------+-----------+-------------+-----------------+---------+--------+---------------+------------+----------+----...
    |    Washington|    Washington|    Adams|    Jefferson|    Jefferson|    Madison|    Madison|    Monroe|    Monroe|    John Quincy Adams|    Jackson|    Jackson|    Van Buren|    Harrison DIES|    Tyler|    Polk|    Taylor DIES|    Fillmore|    Pierce|    ...
    +--------------+--------------+---------+-------------+-------------+-----------+-----------+----------+----------+---------------------+-----------+-----------+-------------+-----------------+---------+--------+---------------+------------+----------+----...
       NB. split into words
       ;;:&.><;._2[1!:1<'input.txt'
    +----------+----------+-----+---------+---------+-------+-------+------+------+----+------+-----+-------+-------+---+-----+--------+----+-----+----+------+----+--------+------+--------+-------+-------+----+-------+-----+-----+-----+--------+----+------+---...
    |Washington|Washington|Adams|Jefferson|Jefferson|Madison|Madison|Monroe|Monroe|John|Quincy|Adams|Jackson|Jackson|Van|Buren|Harrison|DIES|Tyler|Polk|Taylor|DIES|Fillmore|Pierce|Buchanan|Lincoln|Lincoln|DIES|Johnson|Grant|Grant|Hayes|Garfield|DIES|Arthur|Cle...
    +----------+----------+-----+---------+---------+-------+-------+------+------+----+------+-----+-------+-------+---+-----+--------+----+-----+----+------+----+--------+------+--------+-------+-------+----+-------+-----+-----+-----+--------+----+------+---...
       NB. count reptititions
       |:~.(,.~[:<"0@(+/)=/~);;:&.><;._2[1!:1<'input.txt'
    +----------+-----+---------+-------+------+----+------+-------+---+-----+--------+----+-----+----+------+--------+------+--------+-------+-------+-----+-----+--------+------+---------+--------+---------+----+------+-------+--------+------+---+------+------...
    |2         |2    |2        |2      |2     |1   |1     |2      |1  |1    |2       |6   |1    |1   |1     |1       |1     |1       |2      |3      |2    |1    |1       |1     |2        |2       |2        |1   |2     |1      |1       |1     |4  |2     |2     ...
    +----------+-----+---------+-------+------+----+------+-------+---+-----+--------+----+-----+----+------+--------+------+--------+-------+-------+-----+-----+--------+------+---------+--------+---------+----+------+-------+--------+------+---+------+------...
    |Washington|Adams|Jefferson|Madison|Monroe|John|Quincy|Jackson|Van|Buren|Harrison|DIES|Tyler|Polk|Taylor|Fillmore|Pierce|Buchanan|Lincoln|Johnson|Grant|Hayes|Garfield|Arthur|Cleveland|McKinley|Roosevelt|Taft|Wilson|Harding|Coolidge|Hoover|FDR|Truman|Eisenh...
    +----------+-----+---------+-------+------+----+------+-------+---+-----+--------+----+-----+----+------+--------+------+--------+-------+-------+-----+-----+--------+------+---------+--------+---------+----+------+-------+--------+------+---+------+------...
       NB. sort
       |:\:~~.(,.~[:<"0@(+/)=/~);;:&.><;._2[1!:1<'input.txt'
    +----+---+-------+----+------+----------+------+---------+------+-----+------+--------+-------+-------+---------+-------+--------+-----+----------+-------+---------+-----+---+-----+------+----+------+----+------+-----+-------+----+------+-----+-------+----...
    |6   |4  |3      |3   |2     |2         |2     |2        |2     |2    |2     |2       |2      |2      |2        |2      |2       |2    |2         |2      |2        |2    |1  |1    |1     |1   |1     |1   |1     |1    |1      |1   |1     |1    |1      |1   ...
    +----+---+-------+----+------+----------+------+---------+------+-----+------+--------+-------+-------+---------+-------+--------+-----+----------+-------+---------+-----+---+-----+------+----+------+----+------+-----+-------+----+------+-----+-------+----...
    |DIES|FDR|Johnson|Bush|Wilson|Washington|Truman|Roosevelt|Reagan|Nixon|Monroe|McKinley|Madison|Lincoln|Jefferson|Jackson|Harrison|Grant|Eisenhower|Clinton|Cleveland|Adams|Van|Tyler|Taylor|Taft|Quincy|Polk|Pierce|Obama|Kennedy|John|Hoover|Hayes|Harding|Garf...
    +----+---+-------+----+------+----------+------+---------+------+-----+------+--------+-------+-------+---------+-------+--------+-----+----------+-------+---------+-----+---+-----+------+----+------+----+------+-----+-------+----+------+-----+-------+----...
       NB. take 10
       10{.\:~~.(,.~[:<"0@(+/)=/~);;:&.><;._2[1!:1<'input.txt'
    +-+----------+
    |6|DIES      |
    +-+----------+
    |4|FDR       |
    +-+----------+
    |3|Johnson   |
    +-+----------+
    |3|Bush      |
    +-+----------+
    |2|Wilson    |
    +-+----------+
    |2|Washington|
    +-+----------+
    |2|Truman    |
    +-+----------+
    |2|Roosevelt |
    +-+----------+
    |2|Reagan    |
    +-+----------+
    |2|Nixon     |
    +-+----------+
    
        6
  •  3
  •   Alan Haggai Alavi    15 年前

    Perl:90

    Perl:114 (包括Perl、命令行开关、单引号和文件名)

    perl -nle'$h{$_}++for split/ /;END{$i++<=10?print"$h{$_} $_":0for reverse sort{$h{$a}cmp$h{$b}}keys%h}' input.txt
    
        7
  •  3
  •   Nick Presta    15 年前

    缺乏 AWK 令人不安。

    xargs -n1<input.txt|awk '{c[$1]++}END{for(p in c)print c[p],p|"sort|tail"}'
    

    75字。

    如果你想让自己更难堪一点,你可以忘记xargs:

    awk -v RS='[^a-zA-Z]' /./'{c[$1]++}END{for(p in c)print c[p],p|"sort|tail"}' input.txt
    
        8
  •  2
  •   please delete me    15 年前

    到目前为止,我最好用Ruby,166个字符:

    h = Hash.new
    File.open('f.l').each_line{|l|l.split(/ /).each{|e|h[e]==nil ?h[e]=1:h[e]+=1}}
    h.sort{|a,b|a[1]<=>b[1]}.last(10).each{|e|puts"#{e[1]} #{e[0]}"}
    

    我很惊讶还没有人发布一个疯狂的J解决方案。

        9
  •  2
  •   Jonathan Leffler    15 年前

    这里是shell脚本的压缩版本,注意为了合理地解释输入数据(没有前导或尾随空格),原始文件中的第二个“tr”和“sed”命令不会更改数据(通过在适当的点插入“teout.n”并检查输出文件大小-相同来验证)。shell需要的空间比人类少——使用cat而不是输入I/O重定向会浪费空间。

    tr \  \\n<input.txt|sort|uniq -c|sort -n|tail -10
    

    它有50个字符,包括脚本末尾的换行符。

    再观察两次(从其他人的回答中得出):

    1. tail 就其本身而言,相当于 tail -10
    2. 在这种情况下,数字和字母排序是等效的,

    这可以再缩小7个字符(到43个,包括尾随新行):

    tr \  \\n<input.txt|sort|uniq -c|sort|tail
    

    使用 xargs -n1 '(没有给出命令前缀)而不是' tr '非常聪明;它处理前导、尾随和多个嵌入空间(这个解决方案没有)。

        10
  •  2
  •   ojblass    15 年前

    VIM 38 并为所有输入工作

    :%!xargs -n1|sort|uniq -c|sort -n|tail
    
        11
  •  2
  •   westmark    15 年前

    Python 2.6, 一百零四 字符:

    l=open("input.txt").read().split()
    for c,n in sorted(set((l.count(w),w) for w in l if w))[-10:]:print c,n
    
        12
  •  2
  •   SilentGhost    15 年前

    蟒蛇 3.1(88字符)

    import collections
    collections.Counter(open('input.txt').read().split()).most_common(10)
    
        13
  •  2
  •   Cuervo's Laugh    7 年前

    修订版 previous entry 它应该保存10个字符:

    h = {}
    File.open('f.1').each {|l|l.split(/ /).each{|e|h[e]==nil ?h[e]=1:h[e]+=1}}
    h.sort{|a,b|a[1]<=>b[1]}.last(10).each{|e|puts"#{e[1]} #{e[0]}"}
    
        14
  •  2
  •   Brad Gilbert    15 年前

    Perl 86字

    94,如果对输入文件名进行计数。

    perl -anE'$_{$_}++for@F;END{say"$_{$_} $_"for@{[sort{$_{$b}<=>$_{$a}}keys%_]}[0..10]}' test.in
    

    如果您不关心得到多少结果,那么它只有75个,不包括文件名。

    perl -anE'$_{$_}++for@F;END{say"$_{$_} $_"for sort{$_{$b}<=>$_{$a}}keys%_}' test.in
    
        15
  •  2
  •   matyr    15 年前

    红宝石66

    puts (a=$<.read.split).uniq.map{|x|"#{a.count x} "+x}.sort.last 10
    
        16
  •  2
  •   Dragan Panjkov    15 年前

    红宝石

    115字符

    w = File.read($*[0]).split
    w.uniq.map{|x| [w.select{|y|x==y}.size,x]}.sort.last(10).each{|z| puts "#{z[1]} #{z[0]}"}
    
        17
  •  2
  •   Helen    15 年前

    Windows批处理文件

    这显然不是最小的解决方案,但我还是决定发布它,只是为了好玩。:)nb:批处理文件使用名为 $ 用于存储临时结果。

    带注释的原始未压缩版本:

    @echo off
    setlocal enableextensions enabledelayedexpansion
    
    set infile=%1
    set cnt=%2
    set tmpfile=$
    set knownwords=
    
    rem Calculate word count
    for /f "tokens=*" %%i in (%infile%) do (
      for %%w in (%%i) do (
    
        rem If the word hasn't already been processed, ...
        echo !knownwords! | findstr "\<%%w\>" > nul
        if errorlevel 1 (
    
          rem Count the number of the word's occurrences and save it to a temp file
          for /f %%n in ('findstr "\<%%w\>" %infile% ^| find /v "" /c') do (
            echo %%n^|%%w >> %tmpfile%
          )
    
          rem Then add the word to the known words list
          set knownwords=!knownwords! %%w
        )
      )
    )
    
    rem Print top 10 word count
    for /f %%i in ('sort /r %tmpfile%') do (
      echo %%i
      set /a cnt-=1
      if !cnt!==0 goto end
    )
    
    :end
    del %tmpfile%
    

    压缩和模糊版本, 三百一十七 字符:

    @echo off&setlocal enableextensions enabledelayedexpansion&set n=%2&set l=
    for /f "tokens=*" %%i in (%1)do for %%w in (%%i)do echo !l!|findstr "\<%%w\>">nul||for /f %%n in ('findstr "\<%%w\>" %1^|find /v "" /c')do echo %%n^|%%w>>$&set l=!l! %%w
    for /f %%i in ('sort /r $')do echo %%i&set /a n-=1&if !n!==0 del $&exit /b
    

    这可以缩短为 二百五十八 如果echo已关闭且命令扩展和延迟变量扩展已打开,则为以下字符:

    set n=%2&set l=
    for /f "tokens=*" %%i in (%1)do for %%w in (%%i)do echo !l!|findstr "\<%%w\>">nul||for /f %%n in ('findstr "\<%%w\>" %1^|find /v "" /c')do echo %%n^|%%w>>$&set l=!l! %%w
    for /f %%i in ('sort /r $')do echo %%i&set /a n-=1&if !n!==0 del $&exit /b
    

    用途:

    > filename.bat input.txt 10 & pause
    

    输出:

    6|DIES
    4|FDR
    3|Johnson
    3|Bush
    2|Wilson
    2|Washington
    2|Truman
    2|Roosevelt
    2|Reagan
    2|Nixon