2017-04-20 105 views
0

這是我的代碼:爲什麼我的代碼爲同一個詞提供不同的數字?

restart = 'y' 
while (True): 
    sentence = input("What is your sentence?: ") 
    sentence_split = sentence.split() 
    lowersen=(sentence.lower()) 
    print(lowersen) 
    sentence2 = [0] 
    for count, i in enumerate(sentence_split): 
     if sentence_split.count(i) < 2: 
      sentence2.append(max(sentence2) + 1) 
     else: 
      sentence2.append(sentence_split.index(i) +1) 
    sentence2.remove(0) 
    print(sentence2) 
    restart = input("would you like restart the programme y/n?").lower() 
    if (restart == "n"): 
      print ("programme terminated") 
      break 
    elif (restart == "y"): 
     pass 
    else: 
     print ("Please enter y or n") 

4號線在輸入句子中的所有單詞轉換爲小寫和第5個顯示在頁面上。但是,如果首先以不同的格式輸入單詞,則單詞被賦予不同的數字。例如,我試用過的代碼,這是顯示的內容:

什麼是你的句子?:你好你好

你好你好

[1,2,3]

你想重新啓動程序Y/N?ñ

程序終止

正如你所看到的,因爲第一個「Hello」擁有資本,它被分配不同數量的第二個這不,即使他們是所謂的兩種轉換成小寫。爲什麼是這樣?我似乎無法找到缺點,所以我需要另一雙眼睛來幫助。

+1

你已經拆分後你lowercasing。嘗試'sentence_split = sentence.lower()。split()'並移除'lowersen'。 – ChatterOne

+0

你是一個救星。這樣一個簡單的錯誤。謝謝。 –

+0

@Milkiemash如果一個問題的答案 - 接受和/或爲幫助你的答案(S)票 - 有沒有必要添加'[回答]'你的問題的標題 - 謝謝。 –

回答

0

你做lowersen=(sentence.lower())事後你永遠不會使用lowersen之價值,因此無論使用值lowersen這樣的:

sentence = input("What is your sentence?: ") 
lowersen=(sentence.lower()) 
sentence_split = lowersen.split() 

或容易oneliner並省略共lowersen:

sentence_split = sentence.lower().split() 
0

尖的通過出在ChatterOne這篇文章的評論,因爲它是lowercasing句子分裂後的代碼沒有工作:

sentence_split = sentence.split() 
lowersen=(sentence.lower()) 

,而它需要手之前完成。

因此,代碼:

sentence_split = sentence.split() 
lowersen=(sentence.lower()) 
print(lowersen) 

需要被改爲:

sentence_split = sentence.lower().split() 
print(sentence.lower()) 
相關問題