为什么Python中的'for word in words:'循环遍历的是单个字符而不是单词?

7
当我在一个字符串words上运行以下代码时:
def word_feats(words):
    return dict([(word, True) for word in words])
print(word_feats("I love this sandwich."))

我得到的输出是一个字母的字典生成式,而不是单词:
```

我得到的输出是一个字母的字典生成式,而不是单词:

```
{'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}

我做错了什么?
2个回答

8

你需要明确地按空格分割字符串:

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

这里使用没有参数的str.split(),在任意宽度的空格(包括制表符和换行符)处分割。否则,一个字符串是单个字符序列,直接迭代将只循环每个字符。
然而,分割成单词必须是您自己执行的显式操作,因为不同的用例将对如何将字符串分成单独的部分有不同的需求。例如,标点符号是否计数?括号或引号呢?也许应该不分割由这些分组的单词?等等。
如果您只是将所有值设置为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}

4
您需要将"words"字符串进行"split"操作:
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}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接