-1

私が抱えている問題は、ファイルに書き込むときに、文()を2回呼び出しているため、ファイル出力がstd.outと異なることです。印刷用に 1 回、書き込み用に 2 回。両方に同じものを出力するにはどうすればよいですか?

最初にファイルに書き込み、次にそれを開いて読み取ることを考えていましたが、それは不器用に思えます。

何か案は?

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

You can simplify this code a lot;

import random

nouns = ["random_noun1","random_noun2","random_noun3"]
adverbs = ["random_adverb1","random_adverb2","random_adverb3"]
verbs = ["random_verb1","random_verb2","random_verb3"]

Your functions random_n(), random_av() and random_v() are the same except they use a different list of words. So according to the DRY principle (Don't Repeat Yourself), make it a single function that takes a parameter. There is no need to store the random choice, because the only thing you do with it is to return it. So the function becomes a one-liner.

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

Use str.join to join a string. :-) There is no need to convert the output of rnd() to a string, because it already is a string.

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

Use a single function to print to stdout and write to a file. This code also gives an example how to use a 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')
于 2013-05-05T11:02:30.517 に答える