计算文本中的单词并显示它们


26

该代码应输入一个文本(不是强制性的,可以是任何文件,stdin,JavaScript字符串等):

This is a text and a number: 31.

输出中应包含单词及其出现次数,并按出现次数降序排列:

a:2
and:1
is:1
number:1
This:1
text:1
31:1

请注意,31是一个单词,所以单词是任何字母数字,数字不充当分隔符,因此例如0xAF有资格成为单词。因此,分隔符将是非字母数字的任何内容,包括.(点)和-(连字符),i.e.否则pick-me-up将导致2个3个单词。应区分大小写,This并且this将是两个不同的词, '也将是如此隔膜wouldn,并t将会从2个不同的字wouldn't

用您选择的语言编写最短的代码。

迄今为止最短的正确答案:


5
大小写是否重要(即Thisthis和相同tHIs)?
Gareth 2014年

如果任何非字母数字的字符都算作分隔符,是wouldn't2个单词(wouldnt)吗?
Gareth 2014年

@Gareth应该区分大小写,This并且this确实是两个不同的词,same wouldnt
Eduard Florinescu 2014年

如果不是两个字,那不是“ Would”和“ nt”,因为这是它的缩写,或者对很多语法学家来说是纳粹主义吗?
Teun Pronk 2014年

@TeunPronk我试图保持简单,放一些规则将鼓励异常与语法保持一致,并且那里有很多异常。英语i.e.中的Ex 是一个单词,但是如果让点在所有短语的结束将采取,用相同的引号或单引号,等等
爱德华Florinescu

Answers:


27

grep和coreutils  44  42

grep -io '[a-z0-9]*'|sort|uniq -c|sort -nr

测试:

printf "This is a text and a number: 31." |
grep -io '[a-z0-9]*'|sort|uniq -c|sort -nr

结果是:

  2 a
  1 This
  1 text
  1 number
  1 is
  1 and
  1 31

更新资料

  • 使用不区分大小写的选项和较短的正则表达式。谢谢托马斯。

2
这几乎是McEllroy对Knuth的著作Literate Programming的回应。唯一的区别是,这不包括最后的管道head
AJMansfield 2014年

这几乎也是我的第一个想法。
罗布

1
'\ w +'也不能正常工作吗?
Sylwester 2014年

1
41个字符grep -io \[A-Z0-9]*|sort|uniq -c|sort -nr
Tomas

1
@Tomas:将此添加到答案中,谢谢。我保留了星号的保护,因为它在某些外壳中扩展了文件名。
雷神

18

Java 8:289

很好,因为java是一种非古怪的语言。

import java.util.stream.*;class C{static void main(String[]a){Stream.of(a).flatMap(s->of(s.split("[\\W_]+"))).collect(Collectors.groupingBy(x->x,Collectors.counting())).entrySet().stream().sorted(x,y->x.getValue()-y.getValue()).forEach(e->System.out.println(e.getKey()+":"+e.getValue()));}

取消高尔夫:

import java.util.stream.*;
class C {
    static void main(String [] args){
        Stream.of(args).flatMap(arg->Stream.of(arg.split("[\\W_]+")))
            .collect(Collectors.groupingBy(word->word,Collectors.counting()))
            .entrySet().stream().sorted(x,y->x.getValue()-y.getValue())
            .forEach(entry->System.out.println(entry.getKey()+":"+entry.getValue()));
    }
}

从命令行运行:

java -jar wordCounter.jar This is a text and a number: 31.

正则表达式分割错误。应该是"[^\\W_]"
n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

@ n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳,该String.split(String regex)方法采用与分隔符匹配的模式进行分割。因此,例如,"aababba".split("b")将产生array {"aa", "a", "", "a"}。我的正则表达式的[^\\w\\d]意思是“单词字符和数字字符类别中的字符”。[^\\W_]而是“既不是下划线也不在非单词字符类中的字符”,并且将匹配除下划线以外的任何单词字符。
AJMansfield 2014年

抱歉,我之前的评论不正确。\w包括\d,因此\d是多余的。\w包括下划线,根据问题应视为下划线。因此,用于拆分的正确正则表达式应为"[\\W_]+"
n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ 2014年

@n thanksh̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳好的,谢谢;我已经解决了这个问题。
AJMansfield 2014年

17

APL(57)

⎕ML←3⋄G[⍒,1↓⍉G←⊃∪↓Z,⍪+⌿∘.≡⍨Z←I⊂⍨(I←⍞)∊⎕D,⎕A,⎕UCS 96+⍳26;]

例如

      ⎕ML←3⋄G[⍒,1↓⍉G←⊃∪↓Z,⍪+⌿∘.≡⍨Z←I⊂⍨(I←⍞)∊⎕D,⎕A,⎕UCS 96+⍳26;]
This is a text and a number: 31.
 a       2
 This    1
 is      1
 text    1
 and     1
 number  1
 31      1

说明:

  • ⎕D,⎕A,⎕UCS 96+⍳26:数字,大写字母,小写字母
  • (I←⍞)∊:读取输入,存储在中I,查看哪些是字母数字
  • Z←I⊂⍨:分为I字母数字字符组,存储在Z
  • +⌿∘.≡⍨Z:对于中的每个元素Z,请查看其发生的频率
  • Z,⍪Z成对匹配每个元素多少次
  • G←⊃∪↓:仅选择唯一的对,存储在 G
  • ⍒,1↓⍉G:获取出现次数的排序索引
  • G[... ;]G按给定索引重新排列行

6
什么...的... f .....
Ozh 2014年

6
这就是为什么我做噩梦。
Thebluefish 2014年

3
@Thebluefish:APL是根据一种符号设计的,其意图就像数学一样,简洁的符号使您可以清晰地思考。就像数学一样,当您第一次看到这种表示法时,您倾向于认为它根本不清楚,但是语言一开始似乎总是很复杂。如果不是全部都在一行上,那会更容易,但是……
Phil H

无论您在APL中想到什么,我都只会看到unicode垃圾,指向方向的箭头和倒置的松树。比J更糟糕
Bebe 2014年

可以用较短⎕shelp.dyalog.com/latest/Content/Language/System%20Functions/...)和新的关键操作(help.dyalog.com/latest/Content/Language/Primitive%20Operators/...):g⌷⍨⊂⍒2⌷⍉g←{⍺,≢⍵}⌸('\w+'⎕s'\0')⍞
NGN

8

C#:153c 144c 142c 111c 115c 118c 114c 113c

(通过“ C#语句”模式下的LINQPad,不包括输入字符串)

版本1:142c

var s = "This is a text and a number: 31."; // <- line not included in count
s.Split(s.Where(c=>!Char.IsLetterOrDigit(c)).ToArray(),(StringSplitOptions)1).GroupBy(x=>x,(k,e)=>new{s,c=e.Count()}).OrderBy(x=>-x.c).Dump();

取消高尔夫:

var s = "This is a text and a number: 31.";
s.Split(                                                     // split string on multiple separators
    s.Where(c => !Char.IsLetterOrDigit(c))                   // get list of non-alphanumeric characters in string
     .ToArray(),                                             // (would love to get rid of this but needed to match the correct Split signature)
    (StringSplitOptions)1                                    // integer equivalent of StringSplitOptions.RemoveEmptyEntries
).GroupBy(x => x, (k, e) => new{ s = k, c = e.Count() })     // count by word
 .OrderBy(x => -x.c)                                         // order ascending by negative count (i.e. OrderByDescending)
 .Dump();                                                    // output to LINQPad results panel

结果:

结果

版本2:114c

[\w]包括_,这是不正确的!;[A-z]包括[ \ ] ^ _ `;确定于[^_\W]+

var s = "This is a text and a number: 31."; // <- line not included in count
Regex.Matches(s, @"[^_\W]+").Cast<Match>().GroupBy(m=>m.Value,(m,e)=>new{m,c=e.Count()}).OrderBy(g=>-g.c).Dump();

取消高尔夫:

Regex.Matches(s, @"[^_\W]+")                                   // get all matches for one-or-more alphanumeric characters
     .Cast<Match>()                                            // why weren't .NET 1 collections retrofitted with IEnumerable<T>??
     .GroupBy(m => m.Value, (m,e) => new{ m, c = e.Count() })  // count by word
     .OrderBy(g => -g.c)                                       // order ascending by negative count (i.e. OrderByDescending)
     .Dump();                                                  // output to LINQPad results panel

结果:(作为版本1)


顺便说一句,对于版本2,您的非高尔夫版本与您的高尔夫版本不匹配。而且,由于您使用文字字符串,因此您可以这样写@"[^_\W]"
n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳14

@ n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳-修正了错字并删除了多余的``以节省1个字符-谢谢!!
jimbobmcgee 2014年

7

R,58个字符

sort(table(unlist(strsplit(scan(,""),"[[:punct:]]"))),d=T)

用法:

sort(table(unlist(strsplit(scan(,""),"[[:punct:]]"))),d=T)
1: This is a text and a number: 31.
9: 
Read 8 items

     a     31    and     is number   text   This 
     2      1      1      1      1      1      1 

这是较短的(49个字符)sort(table(gsub("[[:punct:]]","",scan(,""))),d=T)。不幸的是,这两种解决方案均不适用于wouldn't
djhurio

6

perl6:49个字符

.say for get.comb(/\w+/).Bag.pairs.sort(-*.value)

梳理输入以进行内容匹配\w+,将结果的单词列表放在中Bag,要求它们成对,并按负值对它们进行排序。(该*不管的明星,它不是乘法这里)

输出:

"a" => 2
"This" => 1
"is" => 1
"text" => 1
"and" => 1
"number" => 1
"31" => 1

3
Perl 6吓到我了。
2014年

1
每当我想到一个很酷的语言功能时,我都会在Perl6中寻找它。这就是为什么要花很长时间的原因
Phil H

您可以使用.words代替.comb(/\w+/):) 修剪6个字符
Mouq 2014年

@Mouq:不幸的.words是没有按要求:.
去除

-1。_问题说明下的任何单词都不应包含在内。
n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ 2014年

6

Python 101 97

import re
a=re.split('[_\W]+',input())
f=a.count
for w in sorted(set(a),key=f)[::-1]:print w,f(w)

现在可以与换行符一起使用:

$ python countword.py <<< '"This is    a text and a number: 31, and a\nnewline"'
a 3
and 2
31 1
number 1
newline 1
is 1
text 1
This 1

当文本中包含换行符或连续多个空格时,此功能将无效。
klingt.net 2014年

@ klingt.net已修复。
daniero 2014年

6

PHP-84字节

<?$a=array_count_values(preg_split('/[_\W]+/',$argv[1],0,1));arsort($a);print_r($a);

输入被接受为命令行参数,例如:

$ php count-words.php "This is a text and a number: 31."

示例字符串的输出:

Array
(
    [a] => 2
    [number] => 1
    [31] => 1
    [and] => 1
    [text] => 1
    [is] => 1
    [This] => 1
)

1
它说输入就是您想要的。因此您可以使用$argv[1]
Einacio

@Einacio好电话。
2014年

-1。下划线_不应包含在单词中。
n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ 2014年

已修复@ n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳。
2014年

5

的PowerShell(40)

$s -split"\W+"|group -ca|sort count -des

$ s是一个包含输入字符串的变量。


2
[\W]还不够好-它与我的测试中的空格匹配。而且它不是按降序排序的……
jimbobmcgee 2014年

$s -split"[\W]"|group -ca|where{$_.Name -ne ""}|sort{-$_.Count}让您更接近(当然,还有费用)
jimbobmcgee 2014年

糟糕,我错过了排序部分。很快会解决我的答案。
microbian

或者:$s -split"\W+"|group -ca |sort count -des
Nacimota 2014年

4
-split"\W+"在字符串的最后.和结尾之间匹配一个空字符串;也\W+符合_技术上不允许的比赛
jimbobmcgee 2014年

4

Perl的69

$h{$_}++for<>=~/\w+/g;print"$_: $h{$_}
"for sort{$h{$b}-$h{$a}}keys%h

添加了来自@primo和@protist的建议


1
那排序呢?
daniero 2014年

@daniero,太好了!现在排序!
Dom Hastings

1
我认为那是尽其所能。如果您不介意弃用警告,则ge和之间不需要空格for。同样,<=>可以用代替运算符-
2014年

2
@primo Ahhh -不是<=>天才,而不是Perl线程的高尔夫技巧上的。稍后再更新,谢谢!
Dom Hastings 2014年

1
嘿@protist,也\w包括数字(perl -e 'print for"a 1 2 3 4 b"=~/\w/g'prints a1234b),但是您迭代单词的机制会保存另一个字符,所以我将进行更新。谢谢!
Dom Hastings

4

动力壳:57 55 53 62 57

(不包括输入字符串)

$s = "This is a text and a number: 31."    # <-- not counting this line...
[Regex]::Matches($s,"[^_\W]+")|group -ca|sort{-$_.Count}

返回:

Count Name                      Group
----- ----                      -----
    2 a                         {a, a}
    1 and                       {and}
    1 31                        {31}
    1 number                    {number}
    1 This                      {This}
    1 is                        {is}
    1 text                      {text}

(带有对@microbian的支持,用于-ca组)


3

EcmaScript 6

版本1(108个字符)

s.split(_=/[^a-z\d]/i).map(x=>_[x]=-~_[x]);keys(_).sort((a,b)=>_[a]<_[b]).map(x=>x&&console.log(x+':'+_[x]))

版本2(102个字符)

s.split(_=/[^a-z\d]/i).map(x=>_[x]=-~_[x]);keys(_).sort((a,b)=>_[a]<_[b]).map(x=>x&&alert(x+':'+_[x]))

版本3(105个字符)

s.match(_=/\w+/g).map(x=>_[x]=-~_[x]);alert(keys(_).sort((a,b)=>_[a]<_[b]).map(x=>x+':'+_[x]).join('\n'))

版本4(94个字符)

s.match(_=/\w+/g).map(x=>_[x]=-~_[x]);keys(_).sort((a,b)=>_[a]<_[b]).map(x=>alert(x+':'+_[x]))

版本5(无警报; 87个字符)

s.match(_=/\w+/g).map(x=>_[x]=-~_[x]);keys(_).sort((a,b)=>_[a]<_[b]).map(x=>x+':'+_[x])

版本6(100个字符)

keys(_,s.match(_=/\w+/g).map(x=>_[x]=-~_[x])).sort((a,b)=>_[a]<_[b]).map(x=>console.log(x+':'+_[x]))

输出:

a:2
31:1
This:1
is:1
text:1
and:1
number:1

你可以改变_[a]_[b]_.a_.b。同样更改/\w+/g,_={}_=/\w+/g将产生相同的结果。
eithed

@eithedog谢谢!但是,我不能改变_[a]_.a因为它试图访问该属性"a"_,而不是财产a
牙刷

嗯,正确-无法保留订单。进行:)
eithed

哦,我没注意到你的回答。但是..正在Object.keys成为ES6的全球性吗?您的答案似乎假设是这样,但我不记得看到为ES6计划的那样。
FireFly 2014年

@FireFly我找不到任何文档,但是在Firefox中工作正常。我尚未在Chrome / Opera / IE中对其进行测试。
牙刷

3

Groovy 77 82

将正则表达式从更改[^\w]+[^\d\p{L}]+为了解决下划线问题

String s = 'This is a text and a number: 31'

def a=s.split(/[^\d\p{L}]+/) 
a.collectEntries{[it, a.count(it)]}.sort{-it.value}

没有第一行,82个字符

输出:

[a:2, This:1, is:1, text:1, and:1, number:1, 31:1]

nu_ber不是字母数字。这shouls是2个字
排排坐

为什么用nu_ber代替number
凯文·费根

我被其他一些帖子误导了;)现在我从输入中删除了“ _”,但修复了正则表达式以进行处理
Kamil Mikolajczyk 2014年

3

GNU awk + ​​coreutils:71 69

gawk 'BEGIN{RS="\\W+"}{c[$0]++}END{for(w in c)print c[w],w}'|sort -nr

尽管gawk asort可以在关联数组上运行,但显然并不能保留索引值,因此需要外部sort

printf "This is a text and a number: 31." | 
gawk 'BEGIN{RS="\\W+"}{c[$0]++}END{for(w in c)print c[w],w}'|sort -nr
2 a
1 This
1 text
1 number
1 is
1 and
1 31

GNU awk 4.x:100 93

一个稍大但纯的gawk解决方案,PROCINFO用于设置关联数组的默认排序顺序(似乎需要相对较新的gawk-> 4.x?)

BEGIN{RS="\\W+";PROCINFO["sorted_in"]="@val_num_desc"}
{c[$0]++}
END{for(w in c)print c[w],w}

哦 我不知道PROCINFO。好像我需要另一个借口在生活中使用awk。诅咒你!
dmckee 2014年

@dmckee TBH,直到我开始四处摸索之前,我才不了解PROCINFO-我坚信必须有一种本地处理的方法-只是可惜标识符这么长;)
steeldriver 2014年

在糟糕的过去,根本没有办法。这导致了像我这样的老答案
dmckee 2014年

-1。下划线_不应包含在单词中。
n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ 2014年

3

使用Javascript - 132个 126字符!

(最短的JS代码)

o={},a=[]
for(i in s=s.split(/[\W_]+/))o[z=s[i]]=o[z]+1||1
for(j in o)a.push([j,o[j]])
a.sort(function(b,c){return c[1]-b[1]})

改进了正则表达式和一些编辑。


不打高尔夫球

s = s.split(/[\W_]+/), o={}, a=[]; // split along non-char letters, declare object and array

for (i in s) { n = s[i]; o[n] = o[n] + 1 || 1 } // go through each char and store it's occurence

for (j in o) a.push( [j, o[j]] ); // store in array for sorting

a.sort(function (b, c){ return c[1] - b[1]; }); // sort !

<= // make s =“这天有多亮是不是”

=> [['is',3],
['How',1],
['shiny',1],
['this',1],
['day',1],
['isn',1] ,
['t',1]]


老- 156 143 141 140 132个字符

s=s.split(/[^\w]+/g),o={}
for(i in s){n=s[i];o[n]=o[n]+1||1}a=[]
for(j in o)a.push([j,o[j]])
a.sort(function(b,c){return c[1]-b[1]})

尝试打高尔夫球。反馈表示赞赏。


2

的EcmaScript 6,115 100 87(无提示与警告)

感谢@eithedog:

s.match(/\w+/g,a={}).map(w=>a[w]=-~a[w]),keys(a).map(w=>[w,a[w]]).sort((a,b)=>b[1]-a[1])

具有提示和警报(100):

prompt(a={}).match(/\w+/g).map(w=>a[w]=-~a[w]);alert(keys(a).map(w=>[w,a[w]]).sort((a,b)=>b[1]-a[1]))

在Firefox中运行它。


1
您不需要var 。另外,您可以a={}prompt- 内移动prompt(a={})。您也可以删除Object.和更改w=>a[w]=a[w]+1||1w=>a[w]=-~a[w]
eithed

非常好。现在击败了正在工作的Python :)
teh_senaus 2014年

与@toothbrush的答案相同- a从提示的声明移动到正则表达式将节省两个字符。
eithed

很干净。做得好!
牙刷

-1。下划线_不应包含在单词中。
n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ 2014年

2

红宝石58 82 65

h=Hash.new 0
gets.scan(/[\d\w]+/){h[$&]+=1}
p *h.sort_by{|k,v|-v}

测试运行:

$ ruby counttext.rb <<< "This is a text and a number: 31."
["a", 2]
["text", 1]
["This", 1]
["is", 1]
["and", 1]
["number", 1]
["31", 1]

编辑58-> 80:好的,我走了。我忘记了按出现次数对单词进行排序。另外,Array#uniq它不是枚举器,而是使用给定的块比较元素,因此传递puts给它并不会过滤出重复项(并不是说应该重复)。


1
也许split(/\W+/)代替scan(未试验)?
2014年

@霍华德谢谢。\W不包括在内,_因此必须进行修复,但是它仍然保存了2个字符(然后我添加了20个字符来修复我忽略的排序)。
daniero 2014年

不应该进行排序reverse (a=gets.split(/[_\W]+/)).uniq.map{|w|[w,a.count(w)]}.sort_by(&:last).reverse.map{|x|p x}
爱德华Florinescu

@EduardFlorinescu Nah。reverse是太冗长了;)顺便说一句,改变问题是不公平的。
daniero 2014年

如果您在输出样本中看到它,则仅是我忘记指定它的排序而降序了。
Eduard Florinescu 2014年

2

F#-169

let f s=(s+"").Split(set s-set(['a'..'z']@['A'..'Z']@['0'..'9'])|>Set.toArray)|>Seq.where((<>)"")|>Seq.countBy id|>Seq.sortBy((~-)<<snd)|>Seq.iter((<||)(printfn"%s:%d"))

已脱胶:

let count (s : string) =
    s.Split (set s - set (['a'..'z']@['A'..'Z']@['0'..'9']) |> Set.toArray)
 |> Seq.where ((<>) "")
 |> Seq.countBy id
 |> Seq.sortBy ((~-) << snd)
 |> Seq.iter ((<||) (printfn "%s:%d"))

从fsi调用时的输出:

> "This is a text and a number: 31." |> f
a:2
This:1
is:1
text:1
and:1
number:1
31:1
val it : unit = ()

更新:注释中要求的一些解释。

使用set函数在输入中生成非字母数字字符数组以传递给String.Split,然后使用sequence函数过滤出空字符串,生成字数并打印结果。

打高尔夫球的一些技巧:在函数参数s中添加一个空字符串,以强制将参数的类型推断为字符串,而不是显式声明类型。使用Seq.where而不是Seq.filter来保存一些字符(它们是同义词)。尝试将正向管道和普通功能应用程序混合使用,以尽量减少字符。使用currying和(op)语法来处理<>〜-和<|| 运算符作为常规函数,以避免声明lambda来过滤空字符串,按递减计数排序和打印元组。


您绝对应该插入某种解释;这样我们就可以理解您的代码。
贾斯汀

添加了脱胶版本和一些说明。
mattnewport 2014年

2

Python-95( 由于@primo,现在为 87

d=__import__('re').findall(r'\w+',raw_input())
print sorted(map(lambda y:(y,d.count(y)),d))

样本输入:

'This is a text and a number: 31'

样本输出:

[('This', 1),('is', 1), ('a', 2),('text', 1),('and', 1),('a', 2),('number', 1),('31', 1)]

任何改进建议将不胜感激


1
解决方案很好,但是输出未排序。
Eduard Florinescu 2014年

排序是什么意思?感谢您的评论。
Azwr 2014年

1
\w火柴[a-zA-Z0-9_]。您的整个正则表达式可以替换为r'\w+'。另外,x不需要该变量,只需将其raw_input()用作的第二个参数即可findall
primo 2014年

通过排序,OP意味着最常出现的单词需要首先列出。另外,您的程序应包含一个print语句(即print map(...),否则它不是完整的程序。
2014年

我没有时间,现在将它整理:(我在赶时间,感谢您的建议和意见。
Azwr

2

的JavaScript 160 144(被修改:满足要求)

f=Function;o={};s.replace(/\w+/g,f('a','o[a]=++o[a]||1'));Object.keys(o).sort(f('b,c','return o[c]-o[b]')).map(f('k','console.log(k+" "+o[k])'))

未缩小:

f=Function;
o = {};
s.replace(/\w+/g, f('a','o[a]=++o[a]||1'));
Object.keys(o).sort(f('b,c', 'return o[c]-o[b]')).map(f('k','console.log(k+" "+o[k])'))

将每个单词按顺序记录到控制台,并传递以下字符串:

s="This is sam}}ple text 31to test the effectiveness of this code, you can clearly see that this is working-as-intended, but you didn't doubt it did you?.";

输出:

you 3
this 2
is 2
can 1
text 1
31to 1
test 1
the 1
effectiveness 1
of 1
This 1
code 1
sam 1
ple 1
clearly 1
see 1
that 1
working 1
as 1
intended 1
but 1
didn 1
t 1
doubt 1
it 1
did 1 

我没有心要使用alert()


1
排序应按数字排序。发生的次数,因此you应该优先。
Eduard Florinescu 2014年

@EduardFlorinescu愚蠢的我...我待会儿解决。
乔治·瑞斯

@EduardFlorinescu已修复
George Reith

-1。下划线_不应包含在单词中。
n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ 2014年

++o[a]||1=>-~o[a]
l4m2 '18

2

k [71个字符]

f:{s:" ",x;`_k!m@k:|(!m)@<.:m:#:'=`$1_'(&~((),/:s)like"[a-zA-Z0-9]")_s}

除字母数字字符外的任何其他字符都将被视为定界符。

f "This is a text and a number: 31."
a     | 2
31    | 1
number| 1
and   | 1
text  | 1
is    | 1
This  | 1

f "won't won won-won"
won| 4
t  | 1

2

Java语言(135)

u=/\w+/g
for(i=s.length;i--;)for(w in a=s.match(u))u[w=a[w]]=u[w]||a.reduce(function(p,c){return p+=w==c},0)==i&&!console.log(w+":"+i)

未缩小:

u=/\w+/g;for (i=s.length;i--;)
    for(w in a=s.match(u))
        u[w=a[w]] = u[w] || 
           a.reduce(function(p,c){return p+=w==c},0)==i && !console.log(w+":"+i)

以降序循环显示每个可能的匹配项数,并输出具有该匹配项数的单词。只是太恐怖了。

注意:Alert会减少一些长度。严格来说,字母数字应为[^\W_]


2

Haskell(153 = 104码+ 49导入)

非常简单,完全组成的函数……甚至不需要参数!这是我的第一次高尔夫,所以轻松一点吧?:)

import Data.Char
import Data.List
import Data.Ord
so=reverse.(sortBy$comparing snd).(map(\t@(x:_)->(x,length t))).group.sort.(map$filter isAlphaNum).words

输出:

*Main> so "This is a text and a number: 31."
[("a",2),("text",1),("number",1),("is",1),("and",1),("This",1),("31",1)]

2

q(50)

desc count each group" "vs ssr[;"[^0-9A-Za-z]";" "]
  • ssr替换非字母数字
  • “” vs将结果拆分为符号列表
  • 计算每个组的计数创建一个字典,该字典将列表中的不同元素与出现次数相匹配
  • desc按降序对字典排序

编辑:修复了意外匹配的ascii 58-64和91-96


1
我不知道,q但是正则表达式是[0-z]基于ASCII的吗?如果是,它还不包括ASCII字符58-64吗?因为那些: ; < = > ? @
jimbobmcgee

伟大的吉姆博布,谢谢
nightTrevors 2014年

别客气; 只是发现是因为我在C#中找到了相同的东西。可悲的是,同样用[A-z],它匹配ASCII 91-96,这是'[\] ^ _``
jimbobmcgee

啊,对了,不错的一点ascii课程!
nightTrevors 2014年

我只是[^_\W]+为我发现的,如果您的语法支持该类,则应为“排除非单词字符和下划线”\W ...
jimbobmcgee 2014年

2

纯Bash(无外部程序),164

这比我希望的要长,但是我想看看是否可以仅使用bash数组(关联和非关联)完成必要的计数和排序(朝正确的方向):

declare -A c
for w in ${@//[[:punct:]]/ };{ ((c[$w]++));}
for w in ${!c[@]};{ i=${c[$w]};((m=i>m?i:m));s[$i]+=$w:;}
for((i=m;i>0;i--));{ printf "${s[i]//:/:$i
}";}

另存为脚本文件chmod +x,然后运行:

$ ./countoccur这是文本和数字:31。
a2
和:1
1号
文字:1
31:1
是:1
这个:1
$ 

2

AWK

awk -vRS='[^A-Za-z0-9]' '$0{c[$0]++}END{for(i in c)print c[i]"\t"i": "c[i]|"sort -nr|cut -f2-"}'

该工作是否没有怪异的扩展:

$ echo 'This is a text and a number: 31.' | awk -vRS='[^A-Za-z0-9]' '$0{c[$0]++}END{for(i in c)print c[i]"\t"i": "c[i]|"sort -nr|cut -f2-"}'
a: 2
This: 1
text: 1
number: 1
is: 1
and: 1
31: 1

如果打印“ count:word”,它会短一些,但是我想模仿给定的示例输出...



1

Python 2.X(108个字符)

print'\n'.join('{}:{}'.format(a,b)for a,b in __import__("collections").Counter(raw_input().split()).items())

Python 3.X(106个字符)

print('\n'.join('{}:{}'.format(a,b)for a,b in __import__("collections").Counter(input().split()).items())

Separators will be anything that is not alpha-numeric-您只能在空白处分割。
daniero 2014年


1

Python 3-76

不幸的是,拆分非字母数字字符的要求将代码扩展了19个字符。以下内容的输出正确显示。如果不确定,请在.most_common()后面添加.Counter(...)

i=__import__
print(i('collections').Counter(i('re').findall('\w+',input())))

输入/输出

给定This is a text and a number: 31.您的输入,将获得以下输出:

Counter({'a': 2, 'is': 1, 'This': 1, 'and': 1, '31': 1, 'number': 1, 'text': 1})

我尝试了其他值,例如

1 2 3 4 5 6 7 8 2 1 5 3 4 6 8 1 3 2 4 6 1 2 8 4 3 1 3 2 5 6 5 4  2 2 4 2 1 3 6

确保,输出顺序不依赖于键的值/哈希。此示例产生:

Counter({'2': 8, '3': 6, '1': 6, '4': 6, '6': 5, '5': 4, '8': 3, '7': 1})

但正如我所说,print(i('collections').Counter(i('re').findall('\w+',input())).most_common())将返回的结果为definitly元组的有序列表。


Python 3-57 (如果空格足以分割:P)

print(__import__('collections').Counter(input().split()))

如果您假设该字符串位于某个变量s中(如其他答案一样),则通过替换input()可能会丢失6个字符。
Phil H

@PhilH好。您是正确的,但我永远都不会超出要求。确定“ JavaScript的字符串”部分可能会建议这样做,但是我显然不能将字符串变量解释为有效的“输入”。但是你是对的。这样会更缩短时间。:P
Dave J

-1。下划线_不应包含在单词中。
n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ 2014年

好吧,这取决于字母数字的定义。在Python中,“ \ w”定义为接受字母数字字符。您可能是正确的,但是通过对规则的这种解释,我的解决方案一直是正确的。:)
戴夫J
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.