Python filter string showing tags less than 2 words

Trying to take a tag string and save only the first 10 that have less than 2 words. I don't know if this code is correct or not ...

mystring = 'one, two, three, three three three, four four four, five, six'

for text in mystring:
    number = len(mystring.split())
        if text >= 2:

print number

basically want to deduce: one, two three, five, six

+3
source share
3 answers
[item.strip() for item in mystring.split(',') if len(item.split()) < 2]

"The result of removing spaces from either end of each of these elements arising from the separation of mysticism into commas, which produces less than two subheadings if they are divided into spaces."

+1
source
>>> mystring = 'one, two, three, three three three, four four four, five, six'
# first separate the string into into a list and strip the extraneous spaces off..
>>> str_list = map(lambda s: s.strip(), mystring.split(','))
# then create a new list where the number of "numbers" in each list item are less or equal than two
>>> my_nums = filter(lambda s: len(s.split()) <= 2, str_list))
>>> print my_nums
['one', 'two', 'three', 'five', 'six']
+2
source

slightly different...

mystring = 'one, two, three, three three, four, five, six'

for text in mystring.split(","):
    number = len(text.strip().split()) #split by default does it by space, and strip removes spaces at both ends of the string
    if number < 2:
        #this string contains less than two words
        print text

first divide by ,, and then for each make a different split, but this time by space.

+1
source

Source: https://habr.com/ru/post/1787564/


All Articles