首页 > 解决方案 > 有没有办法查看 Jupiter Notebook 中的 NLTK 或 Keras 函数?

问题描述

寻找一种方法来选择一个函数并“打开”它以在 Jupiter Notebook 中查看其中的代码。在此先感谢新加入的成员。

作为与该问题相关的旁注,仅查看我之前使用的给定函数的描述的方法如下:

import pydoc
pydoc.help(print) # to see the description of the 'print' function

标签: python-3.xjupyter-notebooknltk

解决方案


利用inspect.getsource

例如,查看内容nltk.word_tokenize

from nltk import word_tokenize
import inspect

lines = inspect.getsource(word_tokenize)
print(lines)

输出:

def word_tokenize(text, language="english", preserve_line=False):
    """
    Return a tokenized copy of *text*,
    using NLTK's recommended word tokenizer
    (currently an improved :class:`.TreebankWordTokenizer`
    along with :class:`.PunktSentenceTokenizer`
    for the specified language).

    :param text: text to split into words
    :type text: str
    :param language: the model name in the Punkt corpus
    :type language: str
    :param preserve_line: An option to keep the preserve the sentence and not sentence tokenize it.
    :type preserve_line: bool
    """
    sentences = [text] if preserve_line else sent_tokenize(text, language)
    return [
        token for sent in sentences for token in _treebank_word_tokenizer.tokenize(sent)
    ]

推荐阅读