簡體   English   中英

為什么我的代碼為同一個單詞給出不同的數字?

[英]Why is my code give different numbers for the same word?

這是我的代碼:

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”具有大寫字母,所以即使第二個都被轉換為小寫字母,第二個也沒有。 為什么是這樣? 我似乎找不到故障,所以我需要另一雙眼睛來幫助。

您執行lowersen=(sentence.lower()) ,此后再也不使用lowersen的值,因此可以使用lowersen的值,例如:

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

或簡單的oneliner並完全省略下層:

sentence_split = sentence.lower().split()

正如ChatterOne在這篇文章的評論中所指出的那樣,該代碼無法使用,因為它在句子被分割后是小寫的:

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

而它需要事先完成。

因此,代碼:

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

需要更改為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM