诗歌语料库
首先,我们利用Python爬虫来爬取诗歌,制作语料库。爬取的网址为: https://www.gushiwen.org,页面如下 :
由于本文主要为试了展示该项目的思路,因此,只爬取了该页面中的唐诗三百首、古诗三百、宋词三百、宋词精选,一共大约1100多首诗歌。为了加速爬虫,采用并发实现爬虫,并保存到poem.txt文件。完整的Python程序如下:
import reimport requestsfrom bs4 import BeautifulSoupfrom concurrent.futures import ThreadPoolExecutor,wait,ALL_COMPLETED# 爬取的诗歌网址urls = ['https://so.gushiwen.org/gushi/tangshi.aspx','https://so.gushiwen.org/gushi/sanbai.aspx','https://so.gushiwen.org/gushi/songsan.aspx','https://so.gushiwen.org/gushi/songci.aspx' ]poem_links = []# 诗歌的网址for url in urls: # 请求头部 headers = {'User-Agent': 'Mozilla/5.0 (windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/67.0.3396.87 Safari/537.36'} req = requests.get(url,headers=headers) soup = BeautifulSoup(req.text,"lxml") content = soup.find_all('div',class_="sons")[0] links = content.find_all('a') for link in links: poem_links.append('https://so.gushiwen.org'+link['href'])poem_List = []# 爬取诗歌页面def get_poem(url): #url = 'https://so.gushiwen.org/shiwenv_45c396367f59.aspx' # 请求头部 headers = {'User-Agent': 'Mozilla/5.0 (windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,"lxml") poem = soup.find('div',class_='contson').text.strip() poem = poem.replace(' ','') poem = re.sub(re.compile(r"([sS]*?)"),'',poem) poem = re.sub(re.compile(r"([sS]*?)"),poem) poem = re.sub(re.compile(r"。([sS]*?)"),poem) poem = poem.replace('!','!').replace('?','?') poem_List.append(poem)# 利用并发爬取executor = ThreadPoolExecutor(max_workers=10) # 可以自己调整max_workers,即线程的个数# submit()的参数: 第一个为函数, 之后为该函数的传入参数,允许有多个future_tasks = [executor.submit(get_poem,url) for url in poem_links]# 等待所有的线程完成,才进入后续的执行wait(future_tasks,return_when=ALL_COMPLETED)# 将爬取的诗句写入txt文件poems = List(set(poem_List))poems = sorted(poems,key=lambda x:len(x))for poem in poems: poem = poem.replace('《','').replace('》','') .replace(':','').replace('“','') print(poem) with open('F://poem.txt','a') as f: f.write(poem) f.write('')
私信小编001获取精心准备的教程大礼包,入门很简单!
import reimport picklefrom xpinyin import Pinyinfrom collections import defaultdictdef main(): with open('F://poem.txt','r') as f: poems = f.readlines() sents = [] for poem in poems: parts = re.findall(r'[sS]*?[。?!]',poem.strip()) for part in parts: if len(part) >= 5: sents.append(part) poem_dict = defaultdict(List) for sent in sents: print(part) head = Pinyin().get_pinyin(sent,tone_marks='marks',splitter=' ').split()[0] poem_dict[head].append(sent) with open('./poemDict.pk','wb') as f: pickle.dump(poem_dict,f)main()
我们可以看一下该pickle文件(poemDict.pk)的内容:
改写为
data_path = os.path.join(os.getcwd(),'Mandarin.dat')
这样我们就完成了mypinyin.py文件。
接下来,我们需要编写诗歌接龙的代码(Poem_JIElong.py),完整代码如下:
import picklefrom mypinyin import Pinyinimport randomimport ctypesSTD_input_HANDLE = -10STD_OUTPUT_HANDLE = -11STD_ERROR_HANDLE = -12FOREGROUND_DARKWHITE = 0x07 # 暗白色FOREGROUND_BLUE = 0x09 # 蓝色FOREGROUND_GREEN = 0x0a # 绿色FOREGROUND_SKYBLUE = 0x0b # 天蓝色FOREGROUND_RED = 0x0c # 红色FOREGROUND_PINK = 0x0d # 粉红色FOREGROUND_YELLOW = 0x0e # 黄色FOREGROUND_WHITE = 0x0f # 白色std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)# 设置CMD文字颜色def set_cmd_text_color(color,handle=std_out_handle): Bool = ctypes.windll.kernel32.SetConsoleTextAttribute(handle,color) return Bool# 重置文字颜色为暗白色def resetcolor(): set_cmd_text_color(FOREGROUND_DARKWHITE)# 在CMD中以指定颜色输出文字def cprint(mess,color): color_dict = { '蓝色': FOREGROUND_BLUE,'绿色': FOREGROUND_GREEN,'天蓝色': FOREGROUND_SKYBLUE,'红色': FOREGROUND_RED,'粉红色': FOREGROUND_PINK,'黄色': FOREGROUND_YELLOW,'白色': FOREGROUND_WHITE } set_cmd_text_color(color_dict[color]) print(mess) resetcolor()color_List = ['蓝色','绿色','天蓝色','红色','粉红色','黄色','白色']# 获取字典with open('./poemDict.pk','rb') as f: poem_dict = pickle.load(f)#for key,value in poem_dict.items(): #print(key,value)MODE = str(input('Choose MODE(1 for 人工接龙,2 for 机器接龙): '))while True: try: if MODE == '1': enter = str(input('请输入一句诗或一个字开始:')) while enter != 'exit': test = Pinyin().get_pinyin(enter,splitter=' ') tail = test.split()[-1] if tail not in poem_dict.keys(): cprint('无法接这句诗。','红色') MODE = 0 break else: cprint('机器回复:%s'%random.sample(poem_dict[tail],1)[0],random.sample(color_List,1)[0]) enter = str(input('你的回复:'))[:-1] MODE = 0 if MODE == '2': enter = input('请输入一句诗或一个字开始:') for i in range(10): test = Pinyin().get_pinyin(enter,splitter=' ') tail = test.split()[-1] if tail not in poem_dict.keys(): cprint('------>无法接下去了啦...','红色') MODE = 0 break else: answer = random.sample(poem_dict[tail],1)[0] cprint('(%d)--> %s' % (i+1,answer),1)[0]) enter = answer[:-1] print('(*****最多展示前10回接龙。*****)') MODE = 0 except Exception as err: print(err) finally: if MODE not in ['1','2']: MODE = str(input('Choose MODE(1 for 人工接龙,2 for 机器接龙): '))
现在整个项目的结构如下(Mandarin.dat文件从xpinyin模块对应的文件夹下复制过来):
切换至该文件夹,输入以下命令即可生成exe文件:
pyinstaller -F Poem_jIElong.py
生成的exe文件为Poem_jIElong.exe,位于该文件夹的dist文件夹下。为了能够让exe成功运行,需要将poemDict.pk和Mandarin.dat文件复制到dist文件夹下。
测试运行
运行Poem_jIElong.exe文件,页面如下:
本项目的诗歌接龙有两种模式,一种为人工接龙,就是你先输入一句诗或一个字,然后就是计算机回复一句,你回复一句,负责诗歌接龙的规则;另一种模式为机器接龙,就是你先输入一句诗或一个字,机器会自动输出后面的接龙诗句(最多10个)。
先测试人工接龙模式:
再测试机器接龙模式:
源码小编已经打包了,进群:960410445 下载即可!
总结以上是内存溢出为你收集整理的利用Python写了个成语接龙!我弟弟已经玩了三天了!还是玩不过!全部内容,希望文章能够帮你解决利用Python写了个成语接龙!我弟弟已经玩了三天了!还是玩不过!所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)