2015-12-14 74 views
-4

我需要为学校项目制作一个程序。它必须执行Python中的.split()函数。但我必须从头开始编写它。代码来模拟.split()函数在Python中的作用

到目前为止,我无法得到它添加任何超过一个空间的列表,我需要它添加无限数量的字符串。如果我给它多个字符,它就不会离开循环。我也不允许使用break

sent = input("Give a sentence here:") 

List=[] 
Bpoint=0 
Epoint=0 
inString=[Bpoint,Epoint] 

Epoint=+1 
x=True 
while x==True: 
    if Epoint >= len(sent): 
      x=False 
    elif Epoint < len(sent): 
     if sent[Epoint] == chr(32): 
      List.append(inString[Bpoint:Epoint]) 
      Bpoint=Epoint + 1 
      x=False 
      if Epoint >= len(sent): 
       x=False 
      elif Epoint < len(sent): 
       x=True 
     elif sent[Epoint] != chr(32): 
      if Epoint >= len(sent): 
       x=False 
      elif Epoint < len(sent): 
       x=True 
      Epoint=+1 
     else: 
      print ("Somethings wrong. Close and start over.") 
print (List) 
+0

这是否意味着*完全*什么'分裂'呢?例如。它应该采取sep和maxsplit参数以及字符串?你需要使这个功能? –

回答

3

下面是我将如何解决这个问题。

首先,重命名变量,收拾风格:

sentence = input("Give a sentence here:") 

results = [] 
word_start = 0 
word_end = 0 
in_string = [word_start, word_end] 

word_end = 1 
running = True 

while running: 
    if word_end >= len(sentence): 
     running = False 
     continue 

    # If we get here, we know that `word_end < len(sentence)` 
    if sentence[word_end] == " ": # chr(32) was just confusing 
     results.append(sentence[word_start:word_end]) # Note that using inString was wrong here 
     word_start = word_end + 1 
     running = False 
     if word_end >= len(sentence): 
      running = False 
     else: # We know `word_end < len(sent)` must be True 
      running = True 

    else: # We know `sentence[word_end] != " "` must be True, no need to check 
     if word_end >= len(sent): 
      running = False 
     else: # No need for the elif check, because logic 
      running = True 
     word_end += 1 # Fixed typo error =+ vs += 
    # else: The 'something wrong' could never be reached. Either a character is a space, or not a space - there is no 3rd option! 

print(results) 

的代码是从一个结构上看大致维持不变,但至少现在它更容易看到发生了什么事情。下一阶段是开始修复结构。我注意到的第一件事是我们有词的开始和结束词计数器,我们需要手动维护它们。这有点难看,所以我们可以用一个for循环代替while循环,这个循环在句子上是enumerate。我还注意到,in_string不能正常使用,所以我们将摆脱它:所以现在

sentence = input("Give a sentence here:") 

results = [] 
word_start = 0 

for current_index, letter in enumerate(sentence): 

    if sentence[current_index] == " ": 
     # We've found a split between two words. See if we can add the previous word 
     word = sentence[word_start:current_index] 
     results.append(word) 
     word_start = current_index + 1 

     # Look at all the counter logic we've removed! 

print(results) 

我运行它,我发现它没有找到的最后一个字:

Give a sentence here:Hi Tom this is a test 
['Hi', 'Tom', 'this', 'is', 'a'] 

所以在我们到了句子结尾之后,我们正在退出循环,因为我们没有足够的空间来触发add-word代码。我们可以通过输入“你好Tom这是一个测试”(注意最后一个空格)证明这个理论:

Give a sentence here:Hi tom this is a test 
['Hi', 'tom', 'this', 'is', 'a', 'test'] 

好了,这就是问题所在,现在我们需要解决它。我会把它留给你:-)之后还有几件事情需要改进/修正(如果你输入"Hello world",会发生什么?),但你需要亲自发现它们!祝你好运!