Given a text I have to find the preceding words to all numbers up to a stop word belonging to a check_words list (kind of stopwords).
check_words = ['the', 'a', 'with','to'] mystring = 'the code to find the beautiful words 78 that i have to nicely check 45 with the snippet' list_of_words = mystring.split()
In that particular text I would check before
'45' and will go backwards up to the point where I find any of the words in check_words (but not more than 8 words).
The code for doing that might be:
preceding_chunks =  for i,word in enumerate(list_of_words): if any(char.isdigit() for char in word): # 8 precedent words (taking into account that I can not slice with 8 back at the beginning) preceding_words = list_of_words[max(0,i-8):i] preceding_words[::-1] # I check from the end of the list towards the start for j,sub_word in enumerate(preceding_words[::-1]): if sub_word in check_words: # printing out j for checking myposition = j print(j) real_preceding_chunk = preceding_words[len(preceding_words)-j:] print(real_preceding_chunk) preceding_chunks.append(real_preceding_chunk) break
This code works. basically I check every word tha But I have the impression (perhaps I am wrong) that it can be achieved with a couple of one liners and hence without loops. Any idea?
NOTE: This question is about improvement the readability of the code, trying to get rid of the loops to make the code faster, and trying to make the code nicer, which is part of the Zen of Python.
NOTE 2: Some previous checks that I did: