2017-04-20 101 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()) 
相关问题