[英]Using conditional variables with nltk's concordance module
我剛剛開始使用nltk,但在使concordance模塊與條件變量一起使用時遇到困難。 我想為拉丁語文本中的任何給定單詞返回一個一致性,但是由於該語言會發生變化,因此我希望能夠指定詞干,識別包含詞干的語料庫中的任何單詞,並為此返回一個一致性。 我使用的代碼是:
book1 = open('Book1.txt', 'rU').read()
token1 = nltk.word_tokenize(book1)
text1 = nltk.Text(token1)
word = raw_input("What stem do you want to search?\n > ")
text1.concordance([w for w in text1 if w.startswith(word)])
返回錯誤:
Traceback (most recent call last):
File "C:\Users\admin\Desktop\start_nltk_horace.py", line 68, in <module>
concordance()
File "C:\Users\admin\Desktop\start_nltk_horace.py", line 49, in concordance
text1.concordance([w for w in text1 if w.startswith(word)])
File "C:\Python27\lib\site-packages\nltk\text.py", line 314, in concordance
self._concordance_index.print_concordance(word, width, lines)
File "C:\Python27\lib\site-packages\nltk\text.py", line 177, in print_concordance
offsets = self.offsets(word)
File "C:\Python27\lib\site-packages\nltk\text.py", line 156, in offsets
word = self._key(word)
File "C:\Python27\lib\site-packages\nltk\text.py", line 312, in <lambda>
key=lambda s:s.lower())
AttributeError: 'list' object has no attribute 'lower'
僅指定text1.concordance(word)
返回我想要的內容,而不會出現任何問題( text1.concordance(word)
我輸入了完全拒絕的單詞),但是我必須重復執行六次函數才能獲得所有不同內容的一致性一個詞的變形。
我認為問題在於,當它僅接受字符串時,您正在嘗試向NLTK的concordance()
函數提供單詞列表。 請嘗試以下操作:
my_concordances = []
my_inputs = [elem for elem in text1 if elem.startswith(word)]
for input in my_inputs:
my_concordances.append(text1.concordance(input))
然后, my_concordances
應該以一個列表結尾,其中每個條目都是一個以原始輸入字符串開頭的不同單詞的一致性。 您還可以考慮根據concordance()
函數返回的特定數據類型為my_concordances
預分配空間,因為您只需檢查my_inputs
的長度my_inputs
。 如果有問題,那可能會提高速度。
請注意,您可能也會對此問題感興趣。 在concordance()
上有更詳細的介紹。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.