Windows 批处理文件
这显然不是最小的解决方案,但我还是决定发布它,只是为了好玩。:) 注意:批处理文件使用名为$的临时文件来存储临时结果。
带有注释的原始未压缩版本:
@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%
压缩和混淆版本,317 个字符:
@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 已关闭并且命令扩展和延迟变量扩展已打开,则可以将其缩短为258个字符:
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