我对python来说还比较陌生,我正在遵循一个教程,但是当我尝试使用非常小的示例文本运行此代码时,在第二次排序后会出现此错误。
TypeError:只能将str(而不是“ NoneType”)连接到str
使用较大的文本样本通常不会给我错误。我的问题是如何改善代码并更正此错误?
e2fsck -f /dev/sda2
输出是这样的
from random import choice
import sys
def generateModel(text, order):
model = {}
for i in range(0, len(text) - order):
fragment = text[i:i+order]
next_letter = text[i+order]
if fragment not in model:
model[fragment] = {}
if next_letter not in model[fragment]:
model[fragment][next_letter] = 1
else:
model[fragment][next_letter] += 1
return model
def getNextCharacter(model, fragment):
letters = []
try:
for letter in model[fragment].keys():
for times in range(0, model[fragment][letter]):
letters.append(letter)
return choice(letters)
except Exception as e:
print(e)
def generateText(text, order, length):
model = generateModel(text, order)
currentFragment = text[0:order]
output = ""
for i in range(0, length-order):
newCharacter = getNextCharacter(model, currentFragment)
output += newCharacter
currentFragment = currentFragment[1:] + newCharacter
print(output)
text = "sample text"
if __name__ == "__main__":
generateText(text, 3, 100)