LoginSignup
1
1

単語集計 awk, ruby。英語(19)

Last updated at Posted at 2019-04-15

プログラミング言語AWK

に掲載の単語集計プログラムを利用してきた。

<この項は書きかけです。順次追記します。>

wc.awk
{
gsub(/[`'&%$-.,:;!?^*_~=|@\\\#<>(){}0123456789\[\]"]/," ") 
for (i=1;i<=NF;i++) 
count[$i]++ 
} 
END {for (w in count) 
print w,count[w] | "sort -f" 
}

上記プログラムは、trコマンドで大文字を小文字に変換してあることを前提としている。

$ tr 'a-z' 'A-Z' < infile > outfile
$ awk -f wc.awk infile > outfile

trコマンドでの大文字化(小文字化)
https://qiita.com/Lewuathe/items/4370be45f5d49c5bf72b

wc2.awk
https://researchmap.jp/jomd7nobo-45644/?lang=japanese

wc2.awk
# Print list of word frequencies
# 単語の出現頻度のリストを出力する。
{
    $0 = tolower($0)    # 大小文字の区別をなくす
    gsub(/[^a-z_ \t]/, " ", $0)  # 句読点をとる
    for (i = 1; i <= NF; i++)
        freq[$i]++
}

END {
    for (word in freq)
        printf "%s\t%d\n", word, freq[word]
}
$ awk -f wc2.awk infule > out file

あ、こっちsortしてなかった。
表計算ソフトに読み込んでsortおよび管理。

#ruby

単語頻度を数える
https://sites.google.com/site/rubycocoamemo/Home/ruby-guan-lian/tango-hindo-wo-kazoeru

wc.rb
#!/usr/bin/ruby
# Word Counter for source code in programming language without comment or standard document without 0C .
# ver.0.1 2014.12.29, 
# ver.0.2 2014.12.29, 
# ver.0.3 2014.12.30 standard I/O
# ver.0.4 2015.4.13 downcase
# https://sites.google.com/site/rubycocoamemo/Home/ruby-guan-lian/tango-hindo-wo-kazoeru
# Eddited by Dr. OGAWA Kiyoshi

words = Hash.new(0)
while buf = STDIN.gets
break if buf.chomp == "exit"
buf.downcase.scan(/\w+/) do |word|
words[word] += 1
end
end

print "WORD\tCOUNT\n"

words.sort_by{|word,count| [-count,word]}.each do |word,count|
print "#{word}\t#{count}\n"
end

p.s. 20170709追記

$ chmod 0777 wc.rb
$ ./wc.rb pcd2.txt
./wc.rb: line 11: syntax error near unexpected token `('
./wc.rb: line 11: `words = Hash.new(0)'

p.s. 2017

f = open('sample.txt')
data = f.read()

# counting
words = {}
for word in data.split():
    words[word] = words.get(word, 0) + 1

# sort by count
d = [(v,k) for k,v in words.items()]
d.sort()
d.reverse()
for count, word in d[:1000]:
    print count, word

参考資料(reference)

「Rubyで英語記事に含まれてる英単語を数えて出現数順にソートする」をカッコよく書いてみた

英語論文・規格・特許を読むときの作業記録

GCC コメント除去、単語計算

<この記事は個人の過去の経験に基づく個人の感想です。現在所属する組織、業務とは関係がありません。>

文書履歴(document history)

ver. 0.01 初稿
ver. 0.02 誤植訂正 20191205

最後までおよみいただきありがとうございました。

いいね 💚、フォローをお願いします。

Thank you very much for reading to the last sentence.

Please press the like icon 💚 and follow me for your happy life.

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1