我最近一直在阅读nltk文档。我不明白下面的代码。
def dialogue_act_features(post):
features = {}
for word in nltk.word_tokenize(post):
features['contains(%s)' % word.lower()] = True
return features
这是一个用于 NaiveBayesClassifier 的特征提取器,但是做什么
features['contains(%s)' % word.lower()] = True
是什么意思?
我认为这行代码是一种生成字典的方法,但我不知道它是如何工作的。
谢谢
最佳答案
在这段代码中:
>>> 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}
有关详细信息,请参阅
关于python - `features[' contains(%s )' % word.lower()] = True` 在 NLTK 中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29574236/