我遇到的问题是,当我写入文件时,文件输出与 std.out 不同,因为我调用了 sentence() 两次。一次用于打印,一次用于写入。如何向两者输出相同的内容?
我正在考虑先写入文件,然后打开它进行阅读,但这似乎很笨拙。
有任何想法吗?
nouns = ["random_noun1","random_noun2","random_noun3"]
adverbs = ["random_adverb1","random_adverb2","random_adverb3"]
verbs = ["random_verb1","random_verb2","random_verb3"]
def random_n():
random_noun = random.choice(nouns)
return random_noun
def random_av():
random_adverb = random.choice(adverbs)
return random_adverb
def random_v():
random_verb = random.choice(verbs)
return random_verb
def sentence():
s = str(random_n().capitalize()) + " " + str(random_av()) + " " + str(random_v()) + " " + str(random_n() + ".")
return s
def WriteFile(filename,text):
myfile = open(filename, 'a')
print(text,file=myfile)
myfile.close()
def generate():
for generate in range(number_of_sentences()):
print(generate +1, sentence())
谢谢