2014-04-03 123 views
-2

我正在嘗試創建一個爭奪單詞以及句子的程序。我有用於拼寫一個單詞的代碼,但我不知道該怎麼做,以爭奪一個句子。有任何想法嗎? 在此先感謝!Python - 爭奪一個句子

import random 

def main(): 
    word = input("Please enter a word or a sentence (if sentence, add a period to end the sentence: ") 
    if "." in word: 
     print(scramble(word)) 
    else: 
     print(scrambleTwo(word)) 


def scramble(word): 
    char1 = random.randint(1, len(word)-2) 
    char2 = random.randint(1, len(word)-2) 
    while char1 == char2: 
     char2 = random.randint(1, len(word)-2) 
    newWord = "" 

    for i in range(len(word)): 
     if i == char1: 
      newWord = newWord + word[char2] 
     elif i == char2: 
      newWord = newWord + word[char1] 

     else: 

      newWord = newWord + word[i] 

    return newWord 

def scrambleTwo(word): 


main() 
+2

你到底在哪裏卡住了?加擾一個你不明白的詞是什麼使你不能用它來爭奪一個句子?你嘗試了什麼? – MAK

+0

這看起來像功課,但我無法抗拒:你可以將你的句子拆分成單個單詞,然後將它們添加到一個集合中。一個集合的順序是不確定的,所以你會有你的句子炒。 –

+1

我認爲你的函數也可以使用list,所以's = sentence.split()'然後'''.join(scramble(s))''。 – fredtantini

回答

0

您需要split你的句子的空間,像這樣:

word_list = sentence.split(" ") 

,然後搶所得數組中類似的方式你如何搶你的話。

scramble(word_list) 

這需要是一個符合加擾而不是字符串(邏輯將是基本相同的,雖然)的陣列的不同的擾頻功能。

+0

添加以下:DEF scrambleTwo(字): S =字 而小號==字: S = sentence.split(」「) (加擾(S)) 返回小號 – user3495872

+0

詞語分離和字母改變了 - 我將如何改變句子中單詞的順序? – user3495872

0

您的代碼有幾個問題。一個是你可以爭取單個字母的單詞,但你嘗試!你也想要raw_input而不是隻有input。最後的訣竅是使用split來獲取每個單詞,然後您就可以爭奪。這是一個修改版本。

import random 

def main(): 
    word = raw_input(
     "Please enter a word or a sentence " 
     "(if sentence, add a period to end the sentence: ") 
    if not "." in word: 
     print(scramble(word)) 
    else: 
     print(scrambleTwo(word)) 


def scramble(word): 
    if len(word) < 2: 
     return word 

    char1 = random.randint(1, len(word)-2) 
    char2 = random.randint(1, len(word)-2) 
    while char1 == char2: 
     char2 = random.randint(1, len(word)-2) 
    newWord = "" 

    for i in range(len(word)): 
     if i == char1: 
      newWord = newWord + word[char2] 
     elif i == char2: 
      newWord = newWord + word[char1] 

     else: 

      newWord = newWord + word[i] 

    return newWord 

def scrambleTwo(word): 
    bits = word.split(" ") 
    new_sentence_array = [] 
    for bit in bits: 
     if not bit: 
      continue 
     new_sentence_array.append(scramble(bit)) 
    return " ".join(new_sentence_array) 


main()