拉取百度汉语的成语接龙脚本

成语不存在或期望的接龙长度超出可查询范围时会报错,不过凑合能找到部分接龙的成语,记录之。

#encoding:GBK

require 'net/http'
require 'nokogiri'

def get_alist(url)
	puts url
	$stdout.flush
	res = Net::HTTP.get_response(URI.parse(url))
	doc = Nokogiri::HTML res.body
	return doc.xpath("//*[@id='jielong-wrapper']")[0].css('div')[0].css('a')
end

def build_long(ci,long,maxlen)
	url = "http://hanyu.baidu.com/s?wd=#{URI.escape(ci.encode('utf-8'))}&cf=jielong&ptype=idiom"
	alist = get_alist(url)
	i = 1
	alist.each do |a|
		if long.has_key?(a.text) then
			return build_long(a.text,long,maxlen)
		else
			long[a.text] = 0
			return long if long.size > maxlen
			return build_long(a.text,long,maxlen) if alist.size <= i
		end
		i = i + 1
	end
end

start_chengyu = '尔虞我诈'
max_length = 20
long = Hash.new
long = build_long(start_chengyu,long,max_length - 1)
result_file = File.open('成语接龙结果文件.txt','w')
long.each do |k,v|
	result_file.puts k
end

你可能感兴趣的:(脚本语言编程)