-1

我遇到的问题是,当我写入文件时,文件输出与 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())

谢谢

4

3 回答 3

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) 
于 2013-05-05T10:37:46.020 回答
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 原则(Don't Repeat Yourself),让它成为一个带参数的单个函数。没有必要存储随机选择,因为您唯一要做的就是返回它。所以函数变成了单行。

def rnd(l):
    return random.choice(l)

用于str.join连接字符串。:-) 无需将输出转换为rnd()字符串,因为它已经是字符串。

def sentence():
    return ' '.join([rnd(nouns).capitalize(), rnd(adverbs), rnd(verbs)+'.'])

使用单个函数打印到标准输出并写入文件。此代码还提供了如何使用文档字符串的示例。

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')
于 2013-05-05T11:02:30.517 回答
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),当您离开该块时,它会自动关闭您的句柄。

在循环中打开-关闭文件也是一个坏主意,它会给硬盘(和操作系统)带来不必要的压力。

于 2013-05-05T10:26:26.073 回答