-2

I have a challenge in my class that is to split a sentence into a list of separate words using iteration. I can't use any .split functions. Anybody had any ideas?

Adeith
  • 1
  • 1
    Where is your code? – Joao Vitorino Oct 27 '17 at 01:50
  • Tried Googling? – Mark Fitzgerald Oct 27 '17 at 09:27
  • A simple search for "[python]split a sentence" shows this has already been answered. [This](https://stackoverflow.com/questions/743806/how-to-split-a-string-into-a-list) may help. – Mark Fitzgerald Oct 27 '17 at 09:57
  • @MarkFitzgerald, the OP can't use `.split()` and nearly all of the many answers on that page use `.split()`. [One that doesn't](https://stackoverflow.com/a/744046/5771269) addresses natural language issues which are likely to come up as soon as a simple solution is tried. – cdlane Oct 27 '17 at 19:39

2 Answers2

0
sentence = 'how now brown cow'
words = []
wordStartIndex = 0
for i in range(0,len(sentence)):
    if sentence[i:i+1] == ' ':
        if i > wordStartIndex:
            words.append(sentence[wordStartIndex:i])
            wordStartIndex = i + 1
if i > wordStartIndex:
    words.append(sentence[wordStartIndex:len(sentence)])
for w in words:
    print('word = ' + w)   

Needs tweaking for leading spaces or multiple spaces or punctuation.

John Anderson
  • 35,991
  • 4
  • 13
  • 36
0

I never miss an opportunity to drag out itertools.groupby():

from itertools import groupby

sentence = 'How now brown cow?'

words = []

for isalpha, characters in groupby(sentence, str.isalpha):
    if isalpha:  # characters are letters
        words.append(''.join(characters))

print(words)

OUTPUT

% python3 test.py
['How', 'now', 'brown', 'cow']
%

Now go back and define what you mean by 'word', e.g. what do you want to do about hyphens, apostrophes, etc.

cdlane
  • 40,441
  • 5
  • 32
  • 81