2012-03-29 4 views
-1

これは文章生成プログラムのコードです。それは、オプションである前置詞句を作成するようにユーザーに求めます(特定の確率で出現する可能性があります)。句をオプションにする方法はわかりません。文章生成プログラムを任意にする

import random 

articles = ("A", "THE")  
nouns = ("BOY", "GIRL", "BAT", "BALL",)  
verbs = ("HIT", "SAW", "LIKED")  
prepositions = ("WITH", "BY") 

def sentence():  
    """Builds and returns a sentence.""" 
    return nounPhrase() + " " + verbPhrase() 

def nounPhrase():  
    """Builds and returns a noun phrase.""" 
    return random.choice(articles) + " " + random.choice(nouns) 

def verbPhrase():  
    """Builds and returns a verb phrase.""" 
    return random.choice(verbs) + " " + nounPhrase() + " " + prepositionalPhrase() 

def prepositionalPhrase():  
    """Builds and returns a prepositional phrase.""" 
    return random.choice(prepositions)+ " " + nounPhrase() 

def main():  
    """Allows the user to input the number of sentences to generate.""" 
    number = input("Enter the number of sentences: ") 
    for count in xrange(0, number): 
     print sentence() 

main() 

答えて

0

あなたは、コマンドライン引数でユーザーのパスは、彼らが前置詞句をしたいかどうかと言って聞かせて、その後のOptionParserでそれを解析できます。彼らは文中の前置詞句を望んでいた場合

parser = OptionParser() 
parser.add_option("-p", "--preposition", dest="prep_phrase", help="Give me a sentence with a prepositional phrase") 
... 
(options, args) = parser.parse_args() 
if options.prep_phrase: 
    ... 

その後、ユーザーは、「./create_sentence.py -p」でプログラムを呼び出します。

1

あなたはこのような何かを見て、あなたの前置詞の機能を書き換えることができます:

def prepositionalPhrase(chance = 0.5): 
    """Builds and returns a prepositional phrase.""" 
    return random.choice(prepositions)+ " " + nounPhrase() if random.random() < chance else "" 

50をrandom.random()関数は0と1の間の乱数を返し、ここで我々は(0.5のデフォルト値を持つパラメータのチャンスを持っています%)の場合、乱数0が1未満の場合はrandom.choice(prepositions) + " " + nounPhrase()を返し、それ以外の場合は空の文字列を返します。この関数preprositionalPhraseに値を渡す必要はありません。なぜなら、デフォルト値の0.5を使用するだけなので、この関数に値を渡す必要はありません。このソリューションとは多少異なることをしたいのであれば、私の答えはあなた自身の解決策を形成するための出発点となります。