Fast chi squared (sum of squared errors) single-character and digram frequency analysis for English text. Lower values = more like English.
Single-character:
$ printf 'hello' | ./chi^2
38.769631
$ printf 'xxxxx' | ./chi^2
2450.795683
Digram:
$ printf 'hello' | ./chi^2 -n 2
175.686545
$ printf 'xxxxx' | ./chi^2 -n 2
15193.678176
If you’re running this in a tight loop, process overhead can be an issue, so you can run it as a daemon on a unix socket, and write to the socket rather than starting a child:
$ ./chi^2 -s /tmp/chi^2.sock -n 2 &
[1] 10963
$ printf "hello" | ncat -U /tmp/chi^2.sock
175.686545
$ printf "xxxxx" | ncat -U /tmp/chi^2.sock
15193.678176
$ kill 10963
[1]+ Done ./chi^2 -s /tmp/chi^2.sock -n 2
n.b. the reason to use printf
here is so that there’s not a newline
after the text.
main.c
is licensed under the MIT license:
Copyright (c) 2016 Elizabeth Morgan Dixon
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
frequencies.c
and digrams.c
were created from the Reuters corpus
available at
http://www.daviddlewis.com/resources/testcollections/reuters21578/ and
the Twitter corpus available
http://help.sentiment140.com/for-students/ respectively, and so may be
considered derivative works. If this is a problem for you, it should
be simple to replace those files.