首先,爬取了两万多的成语。
然后,根据这些成语实现成语接龙。
# 爬虫
library(rvest)
if(F){
# 修改这个
# https://chengyu.911cha.com/pinyin_d.html
# 页码 https://chengyu.911cha.com/pinyin_a_p1.html
url <-"https://chengyu.911cha.com/pinyin_a_p4.html"
# 从网页读取html代码
webpage <- read_html(url,encoding="UTF-8")
idiom <- webpage%>%html_nodes("body div.mainbox div.panel div.mcon ul li")%>%html_text()
rm(url,webpage)
}
# 从这里开始,爬取成语数据 ------------------------------------------------------------
idiom=list()
n=1
for (i in letters) {
print(i)
for (j in 1:20) {
url=paste("https://chengyu.911cha.com/pinyin_",i,"_p",j,".html",sep = "")
webpage <- read_html(url,encoding="UTF-8")
idiom[[n]] <- webpage%>%html_nodes("body div.mainbox div.panel div.mcon ul li")%>%html_text()
if(length(idiom[[n]])==0){
break();
}else{
n=n+1
}
}
}
# 这里就爬取了所有的成语数据,现在要做的就是编写成语接龙
# 随便输入一个成语,返回接下来的成语
idiom_arr=unlist(idiom)
Idioms_solitaire=function(word){
library(stringr)
last_character=str_sub(string = word,start = -1,end = -1)
star_character=str_sub(string = idiom_arr,start = 1,end = 1)
Match_data=idiom_arr[str_detect(str = star_character,pattern = last_character)]
n=sample(1:length(Match_data),1)
return(Match_data[n])
}
# Idioms_solitaire("阿萨大噶")
# 成语接龙 -内部使用了Idioms_solitaire的函数
per_fun=function(word){
result=0
n=1
while (length(Idioms_solitaire(word))!=0&!is.na(word)) {
print(word)
result[n]=word
n=n+1
word=Idioms_solitaire(word)
#Sys.sleep(1)
}
return(result)
}
per_fun("放虎归山")
#[1] "放虎归山"
#[1] "山高皇帝远"
#[1] "远涉重洋"
#[1] "洋洋洒洒"
#[1] "洒洒潇潇"
#[1] "潇洒风流"
#[1] "流水高山"
#[1] "山栖谷隐"
#[1] "隐晦曲折"
#[1] "折戟沉沙"
#[1] "沙鸥翔集"
#[1] "集矢之的"
#[1] "的一确二"
#[1] "二话没说"
#[1] "说东谈西"
#[1] "西方净土"
#[1] "土阶茅屋"
#[1] "屋上乌"
#[1] "乌焦巴弓"
#[1] "弓折刀尽"
#[1] "尽善尽美"
#[1] "美人计"
#[1] "计较锱铢"
#[1] "铢积寸累"
#[1] "累牍连篇"