2016-02-18 5 views
1

Что-то я обнаружил во время работы на this problem был concordance не любит, чтобы отобразить контекст в начале Text:Как работает согласование nltk?

>>> from nltk.book import * 
>>> text3.concordance("beginning",lines=1) 
Displaying 1 of 5 matches: 
            beginning God created the heaven and the ear 

Примечание нет никакого «В» на выходе выше. Однако concordance не имеет проблем с концом Text.

>>> text3.concordance("coffin",lines=1) 
Displaying 1 of 1 matches: 
embalmed him , and he was put in a coffin in Egypt . 

Интересно, что если вы задаете width вещи удаются лучше (по умолчанию width=79, я считаю).

>>> text3.concordance("beginning",width=11, lines=1) 
Displaying 1 of 5 matches: 
In the beginning 

У кого-нибудь есть объяснение? Документ в nltk.org говорит:

Распечатать согласование слова с указанным контекстным окном. Подбор слов не чувствителен к регистру.

ответ

0

Рассмотрим эту функцию concordance, который я модифицированную из исходного кода в class ConcordanceIndex() из исходного кода HERE.

def print_concordance(self, word, width=35, lines=25): 
    """ 
    Print a concordance for ``word`` with the specified context window. 

    :param word: The target word 
    :type word: str 
    :param width: The width of each line, in characters (default=80) 
    :type width: int 
    :param lines: The number of lines to display (default=25) 
    :type lines: int 
    """ 
    #print ("inside:") 
    #print (width) 
    half_width = (width - len(word) - 2) // 2 
    #print (half_width) 
    context = width // 4 # approx number of words of context 
    #print ("Context:"+str(context)) 
    offsets = self.offsets(word) 
    if offsets: 
     lines = min(lines, len(offsets)) 
     print("Displaying %s of %s matches:" % (lines, len(offsets))) 
     for i in offsets: 
      #print(i) 
      if lines <= 0: 
       break 
      left = (' ' * half_width + 
        ' '.join(self._tokens[i-context:i])) #This is were you have to concentrate 
      #print(i-context) 
      #print(self._tokens[i-context:i]) 
      right = ' '.join(self._tokens[i+1:i+context]) 
      left = left[-half_width:] 
      right = right[:half_width] 
      print(left, self._tokens[i], right) 
      lines -= 1 
    else: 
     print("No matches") 

Из комментировал области можно наблюдать, когда значение становится «-ve», то ничего не выводит на консоль.

Вы можете иметь ['+ ve': '- ve'], но не ['-ve': '+ ve']. поэтому ничего не печатается, иначе пустая строка печатается.

Когда self._tokens[i-context:i] первоначально значение будет положительным по мере увеличения ширины, оно будет отрицательным и, следовательно, не будет выхода.

Смежные вопросы