我有一个系列类型的对象,在这个对象中,我必须应用一个函数,该函数使用bigram来更正这个单词,以防它与另一个词同时出现。我创建了一个bigram列表,根据频率(最高值优先)对其进行排序,并将其命名为fdist。
bigrams = [b for l in text2 for b in zip(l.split(" ")[:-1], l.split(" ")[1:])]
freq = nltk.FreqDist(bigrams) #computes freq of occurrence
fdist = freq.keys() # sorted according to freq接下来,我创建了一个函数,它接受每一行(“或句子”、“列表的对象”),并使用bigram来决定是否进一步更正它。
def bigram_corr(line): #function with input line(sentence)
words = line.split() #split line into words
for word1, word2 in zip(words[:-1], words[1:]): #generate 2 words at a time words 1,2 followed by 2,3 3,4 and so on
for i,j in fdist: #iterate over bigrams
if (word2==j) and (jf.levenshtein_distance(word1,i) < 3): #if 2nd words of both match, and 1st word is at an edit distance of 2 or 1, replace word with highest occurring bigram
word1=i #replace
return word1 #return word问题是整个句子只返回一个单词(如:
“往东走”被“让我们”取代。看来,进一步的迭代不起作用。
对于word1,word2的for循环是这样工作的:第一次迭代中的"Lts go“,最终将被”let“替换为”let“,因为let更频繁地出现在"go”中。
在第二次迭代中“往前走”。
第三次迭代中的“走向”。诸若此类。
有一个小错误,我想不出来,请帮帮忙。
发布于 2014-02-18 17:03:14
听起来,您在做word1 = i时,希望这会修改words的内容。但这是不可能的。如果您想修改words,就必须直接修改。使用enumerate跟踪word1的索引。
正如2rs2ts所指出的,您正在提前返回。如果您希望内部循环在找到第一个好的替换后终止,那么break而不是返回。然后返回函数的末尾。
def bigram_corr(line): #function with input line(sentence)
words = line.split() #split line into words
for idx, (word1, word2) in enumerate(zip(words[:-1], words[1:])):
for i,j in fdist: #iterate over bigrams
if (word2==j) and (jf.levenshtein_distance(word1,i) < 3): #if 2nd words of both match, and 1st word is at an edit distance of 2 or 1, replace word with highest occurring bigram
words[idx] = i
break
return " ".join(words)发布于 2014-02-18 16:59:27
return语句完全停止该函数。你想要的是:
def bigram_corr(line):
words = line.split()
words_to_return = []
for word1, word2 in zip(words[:-1], words[1:]):
for i,j in fdist:
if (word2==j) and (jf.levenshtein_distance(word1,i) < 3):
words_to_return.append(i)
return ' '.join(words_to_return)这会将您处理过的每个单词放入一个列表中,然后用空格重新加入它们并返回整个字符串,因为您说了一些关于返回“整句话”的内容。
我不确定您的代码的语义是否正确,因为我没有jf库或您正在使用的任何东西,因此我无法测试这段代码,因此这可能完全解决问题,也可能不会完全解决问题。但这会有帮助的。
https://stackoverflow.com/questions/21860251
复制相似问题