Newer
Older
txt="Les objectifs de Python en font un langage pedagogique ideal.C'est un langage general-purpose:il s'adapte a toutes les applications"
seperatorList = " ,.;-'\":\n/\\?+()’!°"
n_words = 0
words = []
while len(txt) > 0:
seperation = len(txt)
for sep in seperatorList:
sepPos = txt.find(sep)
if sepPos >= 0 and sepPos < seperation:
seperation = sepPos
if seperation > 0:
n_words+=1
txt=txt[seperation+1:]
elif seperation == 0:
txt=txt[seperation+1:]
else:
words.append(txt)
txt=""
print("Il y a {0} mots dans la phrase.".format(n_words))

Jérôme de Favereau de Jeneret
a validé
# solution alternative sans utiliser "find"
# moins optimale sur de grands textes
in_word = False
words = []
curword = ""
for letter in txt:
if letter in separators:
if in_word:
words.append(curword)
curword = ""
in_word = False
else:
in_word = True
curword += letter
if in_word:
words += curword
print("il y a", len(words), "mot(s)")