我刚刚开始学习马尔科夫模型的实现,并且我正在尝试构建一个自动预测特定单词之前的单词的代码。我想用这个随机词生成一个 100 字的作文(我希望你明白我的意思)。
但是,我的代码只返回一个由一个单词组成的 100 个单词的组合!
我很困惑,我想我错过了一些重要的东西,但我似乎无法理解那是什么。我需要一些帮助。
这是我的代码。
from bs4 import BeautifulSoup
from random import randint
from urllib.request import urlopen
#calculating the total sun of words dictionary
def summ(wordlist):
sump=0
for word, value in wordlist.items():
sump+=value
return sump
def random_index(wordlist):
randomindex=randint(1, summ(wordlist))
for word,value in wordlist.items():
randomindex-=value
if randomindex<=0:
return word
def clean_text(text):
text=text.replace('\n',' ')
text=text.replace('"','')
symbols=['.',',',';',':']
for symbol in symbols:
text=text.replace(symbol,' {} '.format(symbol))
words=text.split(' ')
words=[word for word in words if len(word) != 0]
#creating dictinary and dictionary and defining the appropriate terms
wordict={}
for i in range(1, len(words)):
if words[i-1] not in wordict:
wordict[words[i-1]]={}
if words[i] not in wordict[words[i-1]]:
wordict[words[i-1]][words[1]]=0
wordict[words[i-1]][words[1]]+=1
return wordict
text=str(urlopen('http://pythonscraping.com/files/inaugurationSpeech.txt').read(), 'UTF-8')
wordict=clean_text(text)
length=100
chain=['I']
for i in range(0, length):
newWord= random_index(wordict[chain[-1]])
chain.append(newWord)
print(' '.join(chain))
请随时问我有关代码的任何问题。