我遇到的问题是,当我写入文件时,文件输出与std.out不同,因为我调用了句子()两次。一次用于打印,再次用于写入。如何将它们输出到两者?
我正在考虑首先写入文件,然后将其打开以进行阅读,但这看起来很笨拙。
有什么想法吗?
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())
由于
答案 0 :(得分:1)
只需将返回值存储在变量中,并将其用于打印和写入文件:
def generate():
with open(filename, 'a') as output_file:
for generate in range(number_of_sentences()):
next_sentence = sentence()
print(generate +1, next_sentence)
output_file.write(next_sentence)
答案 1 :(得分:1)
您可以大量简化此代码;
import random
nouns = ["random_noun1","random_noun2","random_noun3"]
adverbs = ["random_adverb1","random_adverb2","random_adverb3"]
verbs = ["random_verb1","random_verb2","random_verb3"]
您的功能random_n()
,random_av()
和random_v()
是相同的,除非他们使用不同的单词列表。因此,根据DRY原则(不要重复自己),使其成为一个带参数的函数。没有必要存储随机选择,因为你唯一要做的就是返回它。所以这个功能变成了单行。
def rnd(l):
return random.choice(l)
使用str.join
加入字符串。 :-)没有必要将rnd()
的输出转换为字符串,因为它已经是一个字符串。
def sentence():
return ' '.join([rnd(nouns).capitalize(), rnd(adverbs), rnd(verbs)+'.'])
使用单个函数打印到stdout并写入文件。此代码还给出了如何使用docstring的示例。
def generate(n, filename):
"""Write a number of random sentences to a file and standard output.
Arguments:
n -- the number of random sentences to write.
filename -- the name of the file to write the sentences to.
"""
with open(filename, 'w+') as outf:
for generate in range(n):
s = sentence()
print(generate + 1, s)
outf.write(s + '\n')
答案 2 :(得分:0)
def generate():
with open(filename, 'a') as fh:
for generate in range(number_of_sentences()):
print(generate +1, sentence())
fh.write(sentence())
不确定变量,但你明白了。
另外还不确定这个print(generate +1, sentence())
是如何工作的,但是自从你编写代码以来,你可能对此有了更好的了解。
python中的with
语句打开您的文件,将其放在占位符中(在本例中为fh
),当您离开该块时,它会自动关闭您的句柄。
在循环中打开工作关闭文件也是一个坏主意,它会不必要地对硬盘驱动器(和操作系统)造成太大压力。