python - `features[' contains(%s )' % word.lower()] = True` 在 NLTK 中是什么意思?

标签 python string dictionary nlp nltk

我最近一直在阅读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/

相关文章:

c - 段错误加载字典。它是由 calloc、sys/stat.h 还是其他原因引起的?

python - 如何在 Windows 上运行的 visualsvn 服务器预提交 Hook 中调用 python 脚本

python - C++到Python的算法(径向对称变换)

arrays - 如何更改数组字典中元素的值?

javascript - NodeJS循环遍历字符串并获得准确的输出

安全地将int转换为C中的字符串

python - 如何在Python中从字典写入多个文件

python - 除非以 super 用户身份运行,否则Pygame音频将无法正常启动

python - 按日期和 OR 条件过滤的 Pandas

c - 从 C 文件中排序单词和数字