import os,requests,re,random
from xpinyin import Pinyin
py=Pinyin().get_pinyin
def getCities():
global html
datafile='D:\地级市大全.html'
if not os.path.isfile(datafile):
url='http://www.hotelaah.com/dijishi.html'
h=headers={'User-Agent':'Mozilla/5.0 Chrome/64'}
html=requests.get(url,headers=h).content.decode('gbk')
with open(datafile,'w') as f:
f.write(html)
with open(datafile) as f:
html=f.read()
def getQuestionBaseAndAnswerBase():
rows=re.findall('([一-龥]+)</a></td>\s+<td>.+?([一-龥]+)',html,re.S)
for row in rows:
city=re.sub('[盟州市区县]$|自治.+?|地区','',row[0])
city=city[:2] if city.endswith('族') else city
city=city[:4] if city.endswith('蒙古') else '伊犁' if city.endswith('哈萨克')\
else city+'版纳' if city=='西双' else city+'南' if city in ['黔东','黔西'] else city
questionBase.append(city)
key=py(city[0])
answerBase[key]=answerBase.get(key,'')+';'+city+':'+row[1]
def beginGame(num):
for x in range(num):
question=random.choice(questionBase)
answer=answerBase.get(py(question[-1]),';无对应城市')[1:].split(';')
print(question,answer,sep='——')
if __name__=='__main__':
getCities()
questionBase=[];answerBase={}
getQuestionBaseAndAnswerBase()
num=1
while num:
num=re.findall('\d{1,3}',input('请输入1000道以内的题目数:'))
if num:
num=int(num[0])
beginGame(num)
print('游戏结束。。。')