下面的Python程序?qū)崿F(xiàn)了通過(guò)從網(wǎng)頁(yè)抓取一篇文章,然后根據(jù)這篇文章來(lái)生成新的文章,這其中的原理就是基于概率統(tǒng)計(jì)的文本分析。
過(guò)程大概就是網(wǎng)頁(yè)抓取數(shù)據(jù)->統(tǒng)計(jì)分析->生成新文章。網(wǎng)頁(yè)抓取數(shù)據(jù)是通過(guò)BeautifulSoup庫(kù)來(lái)抓取網(wǎng)頁(yè)上的文本內(nèi)容。統(tǒng)計(jì)分析這個(gè)首先需要使用ngram模型來(lái)把文章進(jìn)行分詞并統(tǒng)計(jì)頻率。因?yàn)槲恼律芍饕罁?jù)馬爾可夫模型,所以使用了2-gram,這樣可以統(tǒng)計(jì)出一個(gè)單詞出現(xiàn)在另一個(gè)單詞后的概率。生成新文章是基于分析大量隨機(jī)事件的馬爾可夫模型。隨機(jī)事件的特點(diǎn)是在一個(gè)離散事件發(fā)生之后,另一個(gè)離散事件將在前一個(gè)事件的條件下以一定的概率發(fā)生。
fromurllib.requestimporturlopen
fromrandomimportrandint
frombs4importBeautifulSoup
importre
defwordListSum(wordList):
sum=0
forword,valueinwordList.items():
sum=sum+value
returnsum
defretrieveRandomWord(wordList):
randomIndex=randint(1,wordListSum(wordList))
forword,valueinwordList.items():
randomIndex-=value
ifrandomIndex<=0:
returnword
defbuildWordDict(text):
text=re.sub('(\n|\r|\t)+',"",text)
text=re.sub('\"',"",text)
punctuation=[',','.',';',':']
forsymbolinpunctuation:
text=text.replace(symbol,""+symbol+"")
words=text.split('')
words=[wordforwordinwordsifword!=""]
wordDict={}
foriinrange(1,len(words)):
ifwords[i-1]notinwordDict:
wordDict[words[i-1]]={}
ifwords[i]notinwordDict[words[i-1]]:
wordDict[words[i-1]][words[i]]=0
wordDict[words[i-1]][words[i]]=wordDict[words[i-1]][words[i]]+1
returnwordDict
defrandomFirstWord(wordDict):
randomIndex=randint(0,len(wordDict))
returnlist(wordDict.keys())[randomIndex]
html=urlopen("http://www.guancha.cn/america/2017_01_21_390488_s.shtml")
bsObj=BeautifulSoup(html,"lxml")
ps=bsObj.find("div",{"id":"cmtdiv3523349"}).find_next_siblings("p");
content=""
forpinps:
content=content+p.get_text()
text=bytes(content,"UTF-8")
text=text.decode("ascii","ignore")
wordDict=buildWordDict(text)
length=100
chain=""
currentWord=randomFirstWord(wordDict)
foriinrange(0,length):
chain+=currentWord+""
currentWord=retrieveRandomWord(wordDict[currentWord])
print(chain)
buildWordDict(text)函數(shù)接收文本內(nèi)容,生成的內(nèi)容如下
{‘itself’:{‘,’:1},‘night’:{‘sky’:1},‘You’:{‘came’:1,‘will’:1},‘railways’:{‘a(chǎn)ll’:1},‘government’:{‘while’:1,‘,’:1,‘is’:1},‘you’:{‘now’:1,‘open’:1,‘down’:1,‘with’:1,‘.’:6,‘,’:1,‘that’:1},
主要就是生成一個(gè)字典,鍵是文章中所有出現(xiàn)的詞語(yǔ),值其實(shí)也是一個(gè)字典,這個(gè)字典是所有直接出現(xiàn)在鍵后邊的詞語(yǔ)及其出現(xiàn)的頻率。這個(gè)函數(shù)就是ngram模型思想的運(yùn)用。
retrieveRandomWord(wordList)函數(shù)的wordList代表的是出現(xiàn)在上一個(gè)詞語(yǔ)后的詞語(yǔ)列表及其頻率組成的字典,然后根據(jù)統(tǒng)計(jì)的概率隨機(jī)生成一個(gè)詞。這個(gè)函數(shù)是馬爾可夫模型的思想運(yùn)用。
然后運(yùn)行這個(gè)程序會(huì)生成一個(gè)長(zhǎng)度為100的文章,如下面所示
fail.Wewillstirourselves,butwewillneverbefore.Donotshareoneheartandpleasantitbackourjobs.Weareinfusedwiththeorderlyandrailwaysallofthegangsandrobbedourjobsfortheirsuccesswilldeterminethecivilizedworld.Wewilltheirsuccesswillbeagreatmenandhighwaysandmillionstoallbleedtheworld.Itbelongstogreatnationalefforttodefendourproducts,constantlycomplaining,D.Wewillbeignoredagain.ItbelongstoharnesstheexpenseofAmerica.
生成的文章看起來(lái)語(yǔ)法混亂,這也難怪,因?yàn)橹皇亲ト》治鼋y(tǒng)計(jì)了一篇的文章。我想如果可以抓取足夠多的英文文章,數(shù)據(jù)集足夠大那么語(yǔ)法準(zhǔn)確度會(huì)大大提高。
以上內(nèi)容為大家介紹了Python實(shí)現(xiàn)文章自動(dòng)生成,希望對(duì)大家有所幫助,如果想要了解更多Python相關(guān)知識(shí),請(qǐng)關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。http://www.em-kal.com/