Why is the word python in iteration words in letters instead of words?

When I enter the following code:

def word_feats(words):
    return dict([(word, True) for word in words])
print(word_feats("I love this sandwich."))

I get the output in letters instead of words

{'a': True, ' ': True, 'c': True, 'e': True, 'd': True, 'I': True, 'h': True, 'l': True, 'o': True, 'n': True, 'i': True, 's': True, 't': True, 'w': True, 'v': True, '.': True}

What am I doing wrong?

Thank!

+4
source share
2 answers

You need to explicitly split the string into spaces:

def word_feats(words):
    return dict([(word, True) for word in words.split()])

This uses str.split()no arguments, separating spaces of arbitrary width (including tabs and line separators). A string is a sequence of individual characters otherwise, and a direct iteration will really just intersect each character.

, , , , , . , ? , , , , ? Etc.

, , True, dict.fromkeys():

def word_feats(words):
    return dict.fromkeys(words.split(), True)

:

>>> def word_feats(words):
...     return dict.fromkeys(words.split(), True)
... 
>>> print(word_feats("I love this sandwich."))
{'I': True, 'this': True, 'love': True, 'sandwich.': True}
+8

split words:

def word_feats(words):
    return dict([(word, True) for word in words.split()])
print(word_feats("I love this sandwich."))

>>> words = 'I love this sandwich.'
>>> words = words.split()
>>> words
['I', 'love', 'this', 'sandwich.']

:

>>> s = '23/04/2014'
>>> s = s.split('/')
>>> s
['23', '04', '2014']

def word_feats(words):
    return dict([(word, True) for word in words.split()])
print(word_feats("I love this sandwich."))

[OUTPUT]
{'I': True, 'love': True, 'this': True, 'sandwich.': True}
+2

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


All Articles