gpt4 book ai didi

python - 如何将 NLTK 索引结果保存在列表中?

转载 作者:行者123 更新时间:2023-12-02 17:13:44 25 4
gpt4 key购买 nike

我正在使用 NLTK 在文本中查找单词。我需要将索引函数的结果保存到列表中。问题已经问了here但我看不到变化。我尝试通过以下方式查找函数返回值的类型:

type(text.concordance('myword'))

结果是:

<class 'NoneType'>

最佳答案

通过检查 ConcordanceIndex 的来源,我们可以看到结果打印到标准输出。如果redirecting stdout to a file不是一个选项,您必须重新实现 ConcordanceIndex.print_concordance 以便它返回结果而不是将其打印到标准输出。

代码:

def concordance(ci, word, width=75, lines=25):
"""
Rewrite of nltk.text.ConcordanceIndex.print_concordance that returns results
instead of printing them.

See:
http://www.nltk.org/api/nltk.html#nltk.text.ConcordanceIndex.print_concordance
"""
half_width = (width - len(word) - 2) // 2
context = width // 4 # approx number of words of context

results = []
offsets = ci.offsets(word)
if offsets:
lines = min(lines, len(offsets))
for i in offsets:
if lines <= 0:
break
left = (' ' * half_width +
' '.join(ci._tokens[i-context:i]))
right = ' '.join(ci._tokens[i+1:i+context])
left = left[-half_width:]
right = right[:half_width]
results.append('%s %s %s' % (left, ci._tokens[i], right))
lines -= 1

return results

用法:

from nltk.book import text1
from nltk.text import ConcordanceIndex

ci = ConcordanceIndex(text1.tokens)
results = concordance(ci, 'circumstances')

print(type(results))
<class 'list'>

关于python - 如何将 NLTK 索引结果保存在列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47649987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com