在这段代码中:
>>> import nltk
>>> def word_features(sentence):
... features = {}
... for word in nltk.word_tokenize(sentence):
... features['contains(%s)' % word.lower()] = True
... return features
...
...
...
>>> sent = 'This a foobar word extractor function'
>>> word_features(sent)
{'contains(a)': True, 'contains(word)': True, 'contains(this)': True, 'contains(function)': True, 'contains(extractor)': True, 'contains(foobar)': True}
>>>
此行正在尝试填充/填充特征字典。:
features['contains(%s)' % word.lower()] = True
下面是一个简单的python字典示例(详见https://docs.python.org/2/tutorial/datastructures.html#dictionaries):
>>> adict = {}
>>> adict['key'] = 'value'
>>> adict['key']
'value'
>>> adict['apple'] = 'red'
>>> adict['apple']
'red'
>>> adict
{'apple': 'red', 'key': 'value'}
和word.lower() 小写一个字符串,例如
>>> str = 'Apple'
>>> str.lower()
'apple'
>>> str = 'APPLE'
>>> str.lower()
'apple'
>>> str = 'AppLe'
>>> str.lower()
'apple'
当您执行'contains(%s)' % word 时,它会尝试创建字符串contain( 和一个符号运算符,然后是)。符号运算符将分配在字符串之外,例如
>>> a = 'apple'
>>> o = 'orange'
>>> '%s' % a
'apple'
>>> '%s and' % a
'apple and'
>>> '%s and %s' % (a,o)
'apple and orange'
符号运算符类似于str.format() 函数,例如
>>> a = 'apple'
>>> o = 'orange'
>>> '%s and %s' % (a,o)
'apple and orange'
>>> '{} and {}'.format(a,o)
'apple and orange'
因此,当代码执行'contains(%s)' % word 时,它实际上是在尝试生成这样的字符串:
>>> 'contains(%s)' % a
'contains(apple)'
当您将该字符串作为键放入字典时,您的键将如下所示:
>>> adict = {}
>>> key1 = 'contains(%s)' % a
>>> value1 = True
>>> adict[key1] = value1
>>> adict
{'contains(apple)': True}
>>> key2 = 'contains(%s)' % o
>>> value = 'orange'
>>> value2 = False
>>> adict[key2] = value2
>>> adict
{'contains(orange)': False, 'contains(apple)': True}
有关详细信息,请参阅