下面是我將如何解決這個問題。
首先,重命名變量,收拾風格:
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"
,會發生什麼?),但你需要親自發現它們!祝你好運!
這是否意味着*完全*什麼'分裂'呢?例如。它應該採取sep和maxsplit參數以及字符串?你需要使這個功能? –