0

という単語のリストを含むリストがありますwordsrandom_sentence任意の文を使用して呼び出すことができる関数があります。各リストのスポットにあるリスト内の単語をランダムな文で検索し、[0]そのリスト内の対応する単語に切り替えたいと思います。それが理にかなっていることを願っています。

words = [["I", "you"], ["i", "you"], ["we", "you"], ["my", "your"], ["our", "your"]]

def random_sentence(sentence):
   list = sentence.split()
   string = sentence
   for y in list:
      for i in words:
         for u in i:
            if y == u:
              mylist = i[1]
              string = string.replace(y, mylist)
   return string

したがってrandom_sentence("I have a my pet dog") 、「あなたはペットの犬を飼っています」を返す必要があります。私の機能は時々機能しますが、機能しない場合もあります。「あなたは若いとあなた」を生み出すと言うrandom_sentence("I went and we") のは意味がありません。

関数を修正して正しい結果を生成するにはどうすればよいですか?

4

4 に答える 4

1

まず、貼り付けたコードは実行されません。関数定義にアンダースコアの代わりにスペースがあり、何も返されません。

しかし、それを修正した後、コードはまさにあなたが記述したとおりに動作します。

理由を理解するには、 s を追加して各ステップでの動作を確認するか、このprintようなビジュアライザーで実行してみてください。

yisのポイントに到達すると、次のようになり"we"ます。

string = string.replace("we", "you")

しかし、それは のすべて weを置き換えstringますwent

このようにしたい場合は、おそらく次のように のそれぞれを変更yし、最後listjoinそれらを元に戻す必要があります。

def random_sentence(sentence):
    list = sentence.split()
    for index, y in enumerate(list):
        for i in words:
            for u in i:
                if y == u:
                    mylist = i[1]
                    list[index] = mylist
    return ' '.join(list)

これを理解するのが難しいと思うなら、私もそうです。すべての変数名は、1 文字か、誤解を招くような名前です (たとえばmylist、リストでさえありません)。また、i本当に最初の要素だけをチェックしたい場合は、見ています。これが読みやすいかどうかを確認します。

replacements = [["I", "you"], ["i", "you"], ["we", "you"], ["my", "your"], ["our", "your"]]
def random_sentence(sentence):
    words = sentence.split()
    for index, word in enumerate(words):
        for replacement in replacements:
            if word == replacement[0]:
                words[index] = replacement[1]
    return ' '.join(words)

ただし、この問題を解決するためのはるかに優れた方法があります。

まず、単語と置換のペアのリストを用意する代わりに、辞書を使用します。次に、ループ全体を取り除き、読みやすくします (さらに高速化します)。

replacements = {"I": "you", "i": "you", "we": "you", "my": "your", "our": "your"}
def random_sentence(sentence):
    words = sentence.split()
    for index, word in enumerate(words):
        replacement = replacements.get(word, word)
        words[index] = replacement
    return ' '.join(words)

そして、元のリストをその場で変更しようとする代わりに、新しいリストを作成してください:

def random_sentence(sentence):
    result = []
    for word in sentence.split():
        result.append(replacements.get(word, word))
    return ' '.join(result)

次に、これresult = []for …: result.append(…)まさにリスト内包表記の目的です。

def random_sentence(sentence):
    result = [replacements.get(word, word) for word in sentence.split()]
    return ' '.join(result)

…または、実際にはリストを必要としないため、join代わりにジェネレーター式を使用できます。

def random_sentence(sentence):
    return ' '.join(replacements.get(word, word) for word in sentence.split())
于 2013-04-15T10:53:31.443 に答える
0

ここでは、配列の配列ではなく、ディクショナリ/マップの方が理にかなっています。辞書wordsを次のように定義します。

words = {"I":"you", "i":"you", "we":"you","my":"your","our":"your"}

そして、次のように使用します。

def randomsentence(text):
    result = []
    for word in text.split():
        if word in words:  #Check if the current word exists in our dictionary
            result.append(words[word])   #Append the value against the word
        else:
            result.append(word)          

    return " ".join(result)

出力:

>>> randomsentence("I have a my pet dog")
'you have a your pet dog'
于 2013-04-15T10:57:11.110 に答える
0

問題はstring.replace、単語の一部である部分文字列を置き換えることです。次のような回答を手動で作成できます。

def random_sentence(sentence):
    list = sentence.split()
    result = []
    for y in list:
        for i in words:
            if i[0] == y:
                result.append(i[1])
                break
        else:
            result.append(y)


    return " ".join(result)

elseに対応しforないことに注意してくださいif

于 2013-04-15T10:52:53.827 に答える
0
>>> words = {'I': 'you', 'i': 'you', 'we': 'you', 'my': 'your', 'our': 'your'}
>>> def random_sentence(sentence):
        return ' '.join([words.get(word, word) for word in sentence.split()])
>>> random_sentence('I have a my pet dog')
'you have a your pet dog'
于 2013-04-15T11:00:09.477 に答える