Skip to content

Instantly share code, notes, and snippets.

@YuheiNakasaka
Last active December 15, 2015 02:29
Show Gist options
  • Save YuheiNakasaka/5187713 to your computer and use it in GitHub Desktop.
Save YuheiNakasaka/5187713 to your computer and use it in GitHub Desktop.
指定されたURL先の文章に含まれる単語の個数を数える。 ruby seachinko.rb [URL] [検索したい単語] 例) $ruby searchinko.rb http://ja.wikipedia.org/wiki/%E3%83%81%E3%83%B3%E3%82%B3 ちんこ 実行結果:「チンコ - Wikipedia」の中に、「ちんこ」という文字が2個ありました。
#-*- coding: utf-8 -*-
require 'open-uri'
class Searchinko
def initialize(word)
@search_word = word
end
def getTitle(contents)
contents =~ /<title>(.*?)<\/title>/
return $1
end
def getContents(url)
open(url).read
end
def searChinko(contents)
matches = contents.scan(/#{@search_word}/)
return matches
end
def countChinko(chinko)
chinko.count
end
def putsChinko(count,title)
if count == 0
puts "「#{title}」の中に、「#{@search_word}」という文字はありませんでした。"
else
puts "「#{title}」の中に、「#{@search_word}」という文字が#{count}個ありました。"
end
end
end
#実行
url = ARGV[0]
searchinko = Searchinko.new(ARGV[1])
contents = searchinko.getContents(url)
title = searchinko.getTitle(contents)
matches = searchinko.searChinko(contents)
counts = searchinko.countChinko(matches)
searchinko.putsChinko(counts,title)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment