首頁  >  文章  >  後端開發  >  怎麼使用Python寫詩詞接龍程序

怎麼使用Python寫詩詞接龍程序

PHPz
PHPz轉載
2023-05-13 17:37:061653瀏覽

詩歌語料庫

  首先,我們利用Python爬蟲來爬取詩歌,製作語料庫。爬取的頁面如下:

怎麼使用Python寫詩詞接龍程序

爬取的詩歌

#由於本文主要為試了展示該項目的思路,因此,只爬取了該頁面中的唐詩三百首、古詩三百、宋詞三百、宋詞精選,總共約1100多首詩歌。為了加速爬蟲,採用並發實現爬蟲,並儲存到poem.txt檔案。完整的Python程式如下:

import re
import requests
from bs4 import BeautifulSoup
from 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 = {: '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 = {: '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")
   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('
')

該程式爬取了1100多首詩歌,並將詩歌保存至poem.txt文件,形成我們的詩歌語料庫。當然,這些詩歌並不能直接使用,需要清理數據,例如有些詩歌標點不規範,有些並不是詩歌,只是詩歌的序等等,這個過程需要人工操作,雖然稍顯麻煩,但為了後面的詩歌分句效果,也是值得的。

詩歌分句

  有了詩歌語料庫,我們需要對詩歌進行分句,分句的標準為:依照結尾為。 ? !進行分句,這可以用正規表示式實現。之後,將分句好的詩寫成字典:鍵(key)為該句首字的拼音,值(value)為該拼音對應的詩句,並將字典儲存為pickle檔。完整的Python程式碼如下:

import re
import pickle
from xpinyin import Pinyin
from collections import defaultdict

def 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)的內容:

怎麼使用Python寫詩詞接龍程序

##pickle檔案的內容(部分)

當然,一個拼音可以對應多個詩。

詩歌接龍

  讀取pickle文件,編寫程序,以exe檔案形式運行該程式。為了能夠在編譯形成exe檔的時候不出錯,我們需要改寫xpinyin模組的

init.py文件,將該檔案的全部程式碼複製至mypinyin.py,並將程式碼中的下面這句程式碼

data_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                            'Mandarin.dat')

改寫為

data_path = os.path.join(os.getcwd(), 'Mandarin.dat')

這樣我們就完成了mypinyin.py檔。接下來,我們需要編寫詩歌接龍的程式碼(Poem_Jielong.py),完整程式碼如下:

import pickle
from mypinyin import Pinyin
import random
import ctypes

STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE = -11
STD_ERROR_HANDLE = -12

FOREGROUND_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, tone_marks='marks', 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, tone_marks='marks', 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), random.sample(color_list, 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模組對應的資料夾下複製過來):

怎麼使用Python寫詩詞接龍程序

專案檔案

切換至該資料夾,輸入以下指令即可產生exe檔:

pyinstaller -F Poem_jielong.py

產生的exe檔為Poem_jielong.exe,位於該資料夾的dist資料夾下。為了能夠讓exe成功運行,需要將poemDict.pk和Mandarin.dat檔案複製到dist資料夾下。

測試運行

  運行Poem_jielong.exe文件,頁面如下:

怎麼使用Python寫詩詞接龍程序

exe文件開始頁面

#本項目的詩歌接龍有兩種模式,一種為人工接龍,就是你先輸入一句詩或一個字,然後就是計算機回復一句,你回復一句,負責詩歌接龍的規則;另一種模式為機器接龍,就是你先輸入一句詩或一個字,機器會自動輸出後面的接龍詩句(最多10個)。 先測試人工接龍模式:

怎麼使用Python寫詩詞接龍程序

人工接龍

  再測試機器接龍模式:

怎麼使用Python寫詩詞接龍程序

以上是怎麼使用Python寫詩詞接龍程序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除