2012-01-17 18 views
10

Tôi muốn tìm hiểu xem văn bản nào xuất hiện sau khi cá thể trùng lặp trả về. Vì vậy, ví dụ, nếu bạn nhìn vào một ví dụ họ đưa ra trong 'Searching Text' section, họ nhận được sự phù hợp của từ 'quái dị'. Làm thế nào bạn sẽ nhận được từ mà đến ngay sau khi một trường hợp quái dị?Gọi sự phù hợp của NLTK - cách nhận văn bản trước/sau một từ đã được sử dụng?

Trả lời

18
import nltk 
import nltk.book as book 
text1 = book.text1 
c = nltk.ConcordanceIndex(text1.tokens, key = lambda s: s.lower()) 
print([text1.tokens[offset+1] for offset in c.offsets('monstrous')]) 

mang

['size', 'bulk', 'clubs', 'cannibal', 'and', 'fable', 'Pictures', 'pictures', 'stories', 'cabinet', 'size'] 

Tôi thấy điều này bằng cách nhìn lên như thế nào phương pháp concordance được định nghĩa.

Điều này cho thấy text1.concordance được định nghĩa trong /usr/lib/python2.7/dist-packages/nltk/text.py:

In [107]: text1.concordance? 
Type:  instancemethod 
Base Class: <type 'instancemethod'> 
String Form: <bound method Text.concordance of <Text: Moby Dick by Herman Melville 1851>> 
Namespace: Interactive 
File:  /usr/lib/python2.7/dist-packages/nltk/text.py 

Trong tập tin mà bạn sẽ tìm thấy

def concordance(self, word, width=79, lines=25): 
    ... 
     self._concordance_index = ConcordanceIndex(self.tokens, 
                key=lambda s:s.lower()) 
    ...    
    self._concordance_index.print_concordance(word, width, lines) 

Điều này cho thấy làm thế nào để nhanh chóng ConcordanceIndex đối tượng.

Và trong cùng một tập tin bạn cũng sẽ tìm thấy:

class ConcordanceIndex(object): 
    def __init__(self, tokens, key=lambda x:x): 
     ... 
    def print_concordance(self, word, width=75, lines=25): 
     ... 
     offsets = self.offsets(word) 
     ... 
     right = ' '.join(self._tokens[i+1:i+context]) 

Với một số thử nghiệm trong phiên dịch IPython, điều này cho thấy self.offsets('monstrous') đưa ra một danh sách các số (offsets) mà từ monstrous có thể được tìm thấy. Bạn có thể truy cập các từ thực tế với self._tokens[offset], tương tự như text1.tokens[offset].

Từ tiếp theo sau monstrous được cung cấp bởi text1.tokens[offset+1].

Các vấn đề liên quan