>>> from nltk.metrics import jaccard_distance
>>> from nltk import ngrams
>>> sent1 = "This is a foo bar sentence".split()
>>> sent2 = "A bar bar black sheep have you a sentence".split()
>>> set(sent1) # A list of unique words in sent1
set(['a', 'bar', 'sentence', 'This', 'is', 'foo'])
>>> set(sent2) # A list of unique words in sent2
set(['A', 'sheep', 'bar', 'sentence', 'black', 'a', 'have', 'you'])
>>> jaccard_distance(set(sent1), set(sent2))
0.7272727272727273
>>> x = [10, 20, 30] # A list of numbers.
>>> y = 3 # A number to compare against the list.
>>> f = lambda x, y: x - y # A simple function to do x - y
>>> f(10,3)
7
>>> f(20,3)
17
>>> result = (f(num,y) for num in x)
>>> result
<generator object <genexpr> at 0x10cafff00>
>>> list(result)
[7, 17, 27]
在第二个场景中,这是更传统的迭代方式,在循环的每次迭代中都会得到一个整数输出:
>>> for num in x:
... result = f(num, y)
... print(type(result), result)
...
(<type 'int'>, 7)
(<type 'int'>, 17)
(<type 'int'>, 27)
获取两袋单词之间的Jaccard距离,即2个句子的唯一词汇。在
现在,如果是一袋ngrams:
^{pr2}$1.0的Jaccard距离是什么意思?
这意味着比较中的两个序列是完全不同的,在这种情况下,每个句子的ngram是唯一的。在
以前,我们把一个句子串分成字符串列表,当我们比较两个序列时,他们会比较句子中的单词/语法。在
现在如果我们迭代2个单词而不是句子,我们将把单词分成一个字符列表,即
^{3}$为了得到它们之间的Jaccard距离:
现在来回答运营商的问题:
与
您可以尝试做的第一件事是简化代码:
使用名称空间
无需反复键入
nltk.ngrams(...)
,您可以这样做:如果只使用2或3的n-gram顺序,即bigrams或trigrams,您可以:
^{8}$如果你想变得花哨,为你想要的ngram顺序定制一个函数,你可以试试
functools.partial
:使用函数
不是重写
set(nltk.ngrams(word, gram_number))
,而是得到uco(word)
:使用显式+清除变量名
在OP中,您使用了}到底是什么。在
for word in spellings
来迭代拼写,但不清楚spellings
是什么。如果在操作中有一个spellings
的示例输入,这样答案就不需要在黑暗中猜测{从循环和Jaccard距离的用法来看,
spellings
是一个单词列表,因此一个更好的变量名应该是list_of_words
,并且迭代在没有注释的情况下会更清晰,例如for word in list_of_words
。在此外,
entry
变量也不明确,从用法来看,它很可能是您要对单词列表执行的查询,因此可能的变量名是query_word
。在[出来]:
现在,回到操作题。让我们来治疗:
spelling
作为x
,即数字列表entry
为y
,即静态数word
为num
,即数字列表中的一个数字jaccard_distance
asf
,一个简单的减法函数。在如果第一种情况,这种循环序列内联的语法是list comprehension。输出是一个生成器类型,您必须使用
list
具体化生成器,并且在生成器内部,每个元素都是f
的输出:在第二个场景中,这是更传统的迭代方式,在循环的每次迭代中都会得到一个整数输出:
在案例1中:
距离是一个元组,包含拼写中所有单词的值 例如:
在案例2中:
距离将被覆盖,因此距离将只包含最后一个值
^{pr2}$相关问题 更多 >
编程相关推荐