为什么我的代码对同一个词给出不同的数字?

2024-10-03 06:21:40 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

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]

是否重新启动程序是/否?n

节目结束

正如你所看到的,因为第一个“Hello”有一个大写字母,所以它被赋予了一个不同的数字给第二个没有的数字,即使它们都应该被转换成小写字母。为什么会这样?我似乎找不到缺点,所以我需要另一双眼睛来帮忙。你知道吗


Tags: inputifcount数字lowerelsesentencesplit
2条回答

执行lowersen=(sentence.lower())之后就不再使用lowersen的值,因此可以使用lowersen的值,如下所示:

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

或者简单的一句话,完全忽略洛厄森:

sentence_split = sentence.lower().split()

正如查特隆在这篇文章的评论中所指出的,代码不起作用,因为它在句子被拆分后是小写的:

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

然而,这需要提前完成。你知道吗

因此,代码:

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

需要更改为:

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

相关问题 更多 >