import random
foundwords = []
wordsDict = {}
with open("text", "r") as file:
contents = file.read().replace('\n',' ')
words = contents.split(' ')
def findwords(word):
for i in range(len(words) - 1):
if words[i] == word:
if not words[i + 1] == '':
foundwords.append(words[i + 1])
return foundwords
for word in words:
wordsDict.setdefault(word, findwords(word))
# for i in range(len(words) - 1):
# findwords(words[i])
# wordsDict.setdefault(words[i], foundwords)
# del foundwords[:]
def nextword(word):
wordList = wordsDict.get(word.lower())
new = wordList[random.randint(0, len(wordList) - 1)]
return new
def assemble():
final = [words[random.randint(0, len(words))].capitalize()]
final.append(nextword(final[-1]))
print(final)
assemble()
我试图创建一个马尔可夫链项目,但是,我收到以下错误:
Traceback (most recent call last):
File "main.py", line 32, in <module>
assemble()
File "main.py", line 28, in assemble
final.append(nextword(final[0]))
File "main.py", line 23, in nextword
new = wordList[random.randint(0, len(wordList) - 1)]
File "/usr/local/lib/python3.6/random.py", line 220, in randint
return self.randrange(a, b+1)
File "/usr/local/lib/python3.6/random.py", line 198, in randrange
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0,0, 0)
exited with non-zero status
有时这个错误:
Traceback (most recent call last):
File "main.py", line 31, in <module>
assemble()
File "main.py", line 28, in assemble
final.append(nextword(final[0]))
File "main.py", line 23, in nextword
new = wordList[random.randint(0, len(wordList) - 1)]
TypeError: object of type 'NoneType' has no len()
我不知道如何开始解决这个问题。我只是一个初学程序员,所以如果我的代码效率低下或任何事情,我道歉。此外,我不确定这是否可以发布为一个问题,抱歉。