In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Visual operation of Python artifact Jupyter Notebook introduction and structure, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can get something.
Brief introduction
If we want to run Python, there are usually two ways, the first is to run interactively in the interpreter environment of Python or IPython, and another way is for programmers to write a .py file, write python code in the file, and then run it.
If we want to write an article about Python, there is code in it, and we want the code to run on the current page, can we do that?
Yes, that is to use the Jupyter Notebook we are going to introduce today.
Jupyter Notebook
The Jupyter project is separated from the Ipython project, and the two were released together before Ipython3.x. After Ipython4.x, Jupyter was developed and managed as a separate project. Because Jupyter can not only run Python programs, it can also perform the operation of other process programming languages.
Jupyter Notebook consists of three parts. the first part is a web application that provides an interactive interface in which you can run the corresponding code.
The above picture is the interactive interface of NoteBook, we can edit the document, run and so on.
The main functions are as follows:
Code editing in the browser, automatic syntax highlighting, indentation and tab completion / self-test.
The ability to execute code from the browser and append the results of the calculation to the code that generated them.
Use rich media representations such as HTML,LaTeX,PNG,SVG to display the results of the calculation. For example, you can inline a publication-quality drawing that contains matplotlib library rendering.
Edits of rich text in browsers using the Markdown markup language (which can provide comments for code) are not limited to plain text.
The ability to easily include mathematical symbols in markdown units using LaTeX, which is rendered natively by MathJax.
The second part is the NoteBook documentation, which stores the code to run and some description information. Typically, this document is stored with the suffix of .ipynb.
Notebook documents are stored in json and encoded in base64. The advantage of using json is that it is convenient to interact with data on different servers.
In addition to runnable code files, Notebook documents can also store explanatory content such as instructions, which makes a perfect combination of code and interpretation, especially for learning notes.
Notebooks can be exported to a variety of static formats through the nbconvert command, including HTML,reStructuredText,LaTeX,PDF and other formats.
In addition, documents can also be easily shared on the network.
The third part is the core Kernels where the code runs. Through different Kernels combinations, notebook can support running a variety of programs. For example: Python,java,go,R,ruby,nodejs and so on.
These Kernels and notebook communicate with each other through MQ in the form of Json.
Start notebook server
With the document, if we want to run the document, we need to start notebook server.
Jupyter notebook
The following URL: http://127.0.0.1:8888 is enabled by default
You can also specify the .ipynb file to open when you start:
Jupyter notebook my_notebook.ipynb
The specific operation of the notebook interface will not be introduced here, basically similar to the ordinary compiler. You can explore on your own.
The structure of notebook document
Notebook contains multiple cells, and each cell contains multiple lines of text input fields, which can be executed through the Shift-Enter or the play button in the toolbar.
There are three types of cell here, code cells,markdown cells and raw cells.
Code cells
The code unit allows you to edit and write new code and highlight the complete syntax and tabs. The programming language you use depends on the kernel, and the default kernel (IPython) runs Python code.
When the code unit is executed, the code it contains is sent to the kernel associated with the notebook. The result returned from the calculation is then displayed as the output of the cell in the notebook. Output is not limited to text, but there are many other possible forms of output, including matplotlib graphics and HTML tables (for example, tables used in the pandas data analysis package).
Let's look at an example of code cells:
#% import numpy as npmy_arr = np.arange (1000000) my_list = list (range (1000000))
Each cell is separated by #%
Ipython itself also supports a variety of rich text presentation formats, including HTML,JSON,PNG,JPEG,SVG,LaTeX.
Ipython provides a display method, and we can use display to show the object to be rendered:
From IPython.display import display
Display (obj) will look for all possible presentation types of the object, select the most appropriate type to display, and store the results in the Notebook document.
If you want to show a specific type of object, you can do this:
From IPython.display import (display_pretty, display_html, display_jpeg,display_png, display_json, display_latex, display_svg)
Give an example of showing a picture:
From IPython.display import Imagei = Image (filename='../images/ipython_logo.png') idisplay (I)
In the above example, I contains an Image object, which can be displayed by calling I directly, and we can also call display (I).
Other rich text types can refer to Image, which is used in a similar way.
Markdown cells
Markdown is a brief markup language that is very easy to use and widely used, so notebook document also supports the syntax of markdown.
Let's take a look at an example of markdown cell:
#% md``python $pythonPython 3.6.0 | packaged by conda-forge | (default, Jan 13 2017, 23:17:12) [GCC 4.8.2 20140120 (Red Hat 4.8.2-15)] on linuxType "help", "copyright", "credits" or "license" for more information. > a = 5 > > print (a) 5```
The syntax in markdown is available in notebook.
Standard LaTeX and AMS-LaTeX syntax are also supported.
Raw cells
The original cell provides a location where you can write directly to the output. Notebook does not evaluate the contents of the original cell.
Import Jupyter Notebooks as a module
Sometimes we want to import Jupyter Notebooks as a module, but unfortunately, Jupyter Notebooks is not a standard python program, but Python provides some hook programs that make it easy for us to import.
First, we need to import some basic API:
Import io, os, sys, typesfrom IPython import get_ipythonfrom nbformat import readfrom IPython.core.interactiveshell import InteractiveShell
Next, you need to register NotebookFinder to sys.meta_path:
Sys.meta_path.append (NotebookFinder ())
This NotebookFinder is the defined hook.
Let's look at the definition of NotebookFinder:
Class NotebookFinder (object): "" Module finder that locates Jupyter Notebooks "def _ init__ (self): self.loaders = {} def find_module (self, fullname, path=None): nb_path = find_notebook (fullname, path) if not nb_path:returnkey = pathif path:# lists aren't hashablekey = os.path.sep.join (path) if key not in self.loaders:self.loaders [key] = NotebookLoader (path) return self.loaders [key]
Two important methods are used, find_notebook to find notebook, and NotebookLoader to load notebook.
Look at the definition of find_notebook:
Def find_notebook (fullname, path=None): "find a notebook, given its fully qualified name and an optional path This turns" foo.bar ">
Look at the definition of NotebookLoader:
Class NotebookLoader (object): "" Module Loader for Jupyter Notebooks "def _ init__ (self, path=None): self.shell = InteractiveShell.instance () self.path = path def load_module (self, fullname):" import a notebook as a module "path= find_notebook (fullname)" Self.path) print ("importing Jupyter notebook from% s"% path) # load the notebook object with io.open (path, 'ringing, encoding='utf-8') as f: nb = read (f) 4) # create the module and add it to sys.modules # if name in sys.modules: # return sys.modules [name] mod = types.ModuleType (fullname) mod.__file__ = path mod.__loader__ = self mod.__dict__ ['get_ipython'] = get_ipython sys.modules [fullname] = mod # extra work to Ensure that magics that would affect the user_ns # actually affect the notebook module's ns save_user_ns = self.shell.user_ns self.shell.user_ns = mod.__dict__ try: for cell in nb.cells: if cell.cell_type = = 'code': # transform the input to executable Python code = self.shell. Input_transformer_manager.transform_cell (cell.source) # run the code in themodule exec (code Mod.__dict__) finally: self.shell.user_ns = save_user_ns return mod
With them, we can directly import the notebook we wrote ourselves.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.