mirror of
https://github.com/LCTT/TranslateProject.git
synced 2025-03-03 01:10:13 +08:00
Merge remote-tracking branch 'LCTT/master'
This commit is contained in:
commit
e8c7c73c4e
@ -1,22 +1,24 @@
|
||||
[#]: collector: (lujun9972)
|
||||
[#]: translator: (geekpi)
|
||||
[#]: reviewer: ( )
|
||||
[#]: publisher: ( )
|
||||
[#]: url: ( )
|
||||
[#]: reviewer: (wxy)
|
||||
[#]: publisher: (wxy)
|
||||
[#]: url: (https://linux.cn/article-12333-1.html)
|
||||
[#]: subject: (Using pandas to plot data in Python)
|
||||
[#]: via: (https://opensource.com/article/20/6/pandas-python)
|
||||
[#]: author: (Shaun Taylor-Morgan https://opensource.com/users/shaun-taylor-morgan)
|
||||
|
||||
使用 pandas 在 Python 中绘制数据
|
||||
使用 Pandas 在 Python 中绘制数据
|
||||
======
|
||||
Pandas 是一个非常流行的 Python 数据操作库。学习怎样使用它的 API 绘制数据。
|
||||
![Two pandas sitting in bamboo][1]
|
||||
|
||||
在有关基于 Python 的绘图库的系列文章中,我们将对使用 pandas(一种非常流行的 Python 数据操作库)绘图进行概念性研究。Pandas 是 Python 中用于可扩展转换数据的标准工具,它也已成为[从 CSV 和 Excel 格式导入和导出数据][2]的流行方法。
|
||||
> Pandas 是一个非常流行的 Python 数据操作库。学习怎样使用它的 API 绘制数据。
|
||||
|
||||
最重要的是,它还包含一个非常好的绘图 API。这非常方便,你已将数据存储在 pandas DataFrame 中,那么为什么不使用相同的库进行绘制呢?
|
||||

|
||||
|
||||
在本系列中,我们将在每个库中制作相同的多柱状图,以便我们可以比较它们的工作方式。我们将使用的数据是 1966 年至 2020 年的英国大选结果:
|
||||
在有关基于 Python 的绘图库的系列文章中,我们将对使用 Pandas 这个非常流行的 Python 数据操作库进行绘图进行概念性的研究。Pandas 是 Python 中的标准工具,用于对进行数据可扩展的转换,它也已成为[从 CSV 和 Excel 格式导入和导出数据][2]的流行方法。
|
||||
|
||||
除此之外,它还包含一个非常好的绘图 API。这非常方便,你已将数据存储在 Pandas DataFrame 中,那么为什么不使用相同的库进行绘制呢?
|
||||
|
||||
在本系列中,我们将在每个库中制作相同的多条形柱状图,以便我们可以比较它们的工作方式。我们使用的数据是 1966 年至 2020 年的英国大选结果:
|
||||
|
||||
![Matplotlib UK election results][3]
|
||||
|
||||
@ -24,22 +26,19 @@ Pandas 是一个非常流行的 Python 数据操作库。学习怎样使用它
|
||||
|
||||
在继续之前,请注意你可能需要调整 Python 环境来运行此代码,包括:
|
||||
|
||||
* 运行最新版本的 Python([Linux][4]、[Mac][5] 和 [Windows][6] 的说明)
|
||||
* 运行最新版本的 Python(用于 [Linux][4]、[Mac][5] 和 [Windows][6] 的说明)
|
||||
* 确认你运行的是与这些库兼容的 Python 版本
|
||||
|
||||
|
||||
|
||||
数据可在线获得,并可使用 pandas 导入:
|
||||
数据可在线获得,并可使用 Pandas 导入:
|
||||
|
||||
```
|
||||
import pandas as pd
|
||||
df = pd.read_csv('<https://anvil.works/blog/img/plotting-in-python/uk-election-results.csv>')
|
||||
df = pd.read_csv('https://anvil.works/blog/img/plotting-in-python/uk-election-results.csv')
|
||||
```
|
||||
|
||||
完成了。在本系列文章中,我们已经看到了一些令人印象深刻的简单 API,但是 pandas 一定能夺冠。
|
||||
|
||||
要在 x 轴上绘制按`年`和每个党派分组的柱状图,我只需要这样做:
|
||||
现在我们已经准备好了。在本系列文章中,我们已经看到了一些令人印象深刻的简单 API,但是 Pandas 一定能夺冠。
|
||||
|
||||
要在 x 轴上绘制按年份和每个党派分组的柱状图,我只需要这样做:
|
||||
|
||||
```
|
||||
import matplotlib.pyplot as plt
|
||||
@ -47,25 +46,24 @@ ax = df.plot.bar(x='year')
|
||||
plt.show()
|
||||
```
|
||||
|
||||
只有四行,这绝对是我们在本系列中创建的最棒的多柱状图。
|
||||
只有四行,这绝对是我们在本系列中创建的最棒的多条形柱状图。
|
||||
|
||||
我以[宽格式][7]使用数据,这意味着每个党派都有一列:
|
||||
|
||||
|
||||
```
|
||||
year conservative labour liberal others
|
||||
0 1966 253 364 12 1
|
||||
1 1970 330 287 6 7
|
||||
2 Feb 1974 297 301 14 18
|
||||
.. ... ... ... ... ...
|
||||
12 2015 330 232 8 80
|
||||
13 2017 317 262 12 59
|
||||
14 2019 365 202 11 72
|
||||
year conservative labour liberal others
|
||||
0 1966 253 364 12 1
|
||||
1 1970 330 287 6 7
|
||||
2 Feb 1974 297 301 14 18
|
||||
.. ... ... ... ... ...
|
||||
12 2015 330 232 8 80
|
||||
13 2017 317 262 12 59
|
||||
14 2019 365 202 11 72
|
||||
```
|
||||
|
||||
这意味着 pandas 会自动知道我希望如何分组,如果我希望进行不同的分组,pandas 可以很容易地[重组 DataFrame][8]。
|
||||
这意味着 Pandas 会自动知道我希望如何分组,如果我希望进行不同的分组,Pandas 可以很容易地[重组 DataFrame][8]。
|
||||
|
||||
与 [Seaborn][9] 一样,pandas 的绘图功能是 Matplotlib 之上的抽象,这就是为什么要调用 Matplotlib 的 `plt.show()` 函数来实际生成绘图的原因。
|
||||
与 [Seaborn][9] 一样,Pandas 的绘图功能是 Matplotlib 之上的抽象,这就是为什么要调用 Matplotlib 的 `plt.show()` 函数来实际生成绘图的原因。
|
||||
|
||||
看起来是这样的:
|
||||
|
||||
@ -79,15 +77,13 @@ year conservative labour liberal others
|
||||
|
||||
首先,我们可以通过将 Matplotlib 颜色表传递到绘图函数来为柱状图着色:
|
||||
|
||||
|
||||
```
|
||||
from matplotlib.colors import ListedColormap
|
||||
cmap = ListedColormap(['#0343df', '#e50000', '#ffff14', '#929591'])
|
||||
ax = df.plot.bar(x='year', colormap=cmap)
|
||||
```
|
||||
|
||||
我们可以使用绘图函数的返回值设置坐标轴标签和标题,它只是一个 [Matplotlib `Axis` 对象][12]。
|
||||
|
||||
我们可以使用绘图函数的返回值设置坐标轴标签和标题,它只是一个 [Matplotlib 的 Axis 对象][12]。
|
||||
|
||||
```
|
||||
ax.set_xlabel(None)
|
||||
@ -99,15 +95,12 @@ ax.set_title('UK election results')
|
||||
|
||||
![pandas styled plot][13]
|
||||
|
||||
这与上面的 Matplotlib 版本几乎相同,但是只用了 8 行代码而不是 16 行!我内心的[代码高尔夫选手][14]非常高兴。
|
||||
这与上面的 Matplotlib 版本几乎相同,但是只用了 8 行代码而不是 16 行!我内心的[代码高手][14]非常高兴。
|
||||
|
||||
### 抽象必须是可转义的
|
||||
|
||||
与 Seaborn 一样,向下访问 Matplotlib API 进行细节调整的能力确实很有帮助。这是给出抽象[紧急出口][15]使其既强大又简单的一个很好的例子。
|
||||
|
||||
* * *
|
||||
|
||||
_本文基于 Anvil 博客上的[如何使用 Pandas 绘图][16],并获许可以重复使用。_
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
@ -116,7 +109,7 @@ via: https://opensource.com/article/20/6/pandas-python
|
||||
作者:[Shaun Taylor-Morgan][a]
|
||||
选题:[lujun9972][b]
|
||||
译者:[geekpi](https://github.com/geekpi)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
校对:[wxy](https://github.com/wxy)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
@ -1,5 +1,5 @@
|
||||
[#]: collector: (lujun9972)
|
||||
[#]: translator: ( )
|
||||
[#]: translator: (011011100010110101101111)
|
||||
[#]: reviewer: ( )
|
||||
[#]: publisher: ( )
|
||||
[#]: url: ( )
|
||||
|
@ -0,0 +1,83 @@
|
||||
[#]: collector: (lujun9972)
|
||||
[#]: translator: ( )
|
||||
[#]: reviewer: ( )
|
||||
[#]: publisher: ( )
|
||||
[#]: url: ( )
|
||||
[#]: subject: (What do Paketo Buildpacks Mean for Developers and Operators)
|
||||
[#]: via: (https://www.linux.com/audience/developers/what-do-paketo-buildpacks-mean-for-developers-and-operators/)
|
||||
[#]: author: (Swapnil Bhartiya https://www.linux.com/author/swapnil/)
|
||||
|
||||
What do Paketo Buildpacks Mean for Developers and Operators
|
||||
======
|
||||
|
||||
Cloud Foundry Foundation recently announced the launch of [Paketo Buildpacks][1] for cloud native developers and operators. But what’s the difference between Cloud Foundry’s Packet and the Buildpacks announced by CNCF? What does it mean for developers who are already using buildpacks? What kind of community is Cloud Foundry look at building around Paketo? What does the roadmap look like?
|
||||
|
||||
To get answers to these questions and deep dive into Paketo Buildpacks, [Swapnil Bhartiya][2], Founder of TFiR.io spoke with Chip Childers, Executive Director, Cloud Foundry Foundation and Kashyap Vedurmudi, Product Manager at VMware.
|
||||
|
||||
_Here is a lightly edited transcript of the interview:_
|
||||
|
||||
**Swapnil Bhartiya: Today we have two guests, Kashyap Vidurmudi, product manager at VMware, and Chip Childers, executive director of Cloud Foundry. Today we are going to talk about the recently announced Paketo Buildpacks. I don’t want to get into that old debate about Docker files versus Buildpacks, but there are two things that I do want to talk about before we talk about Paketo in specific – compliance and security. How does Paketo Buildpacks solve these two problems?**
|
||||
|
||||
Kashyap Vidurmudi: So, we have a couple of things. We are constantly shipping Buildpacks just whenever upstream security vulnerability comes out, a new language family version, things like that. So Buildpacks make it much easier especially for enterprise users just to continuously make sure that their apps stay up to date, and secure, and compliant. So this is I think a huge value proposition of what Buildpacks offer versus using Docker files to run your apps and to build your apps and production.
|
||||
|
||||
Chip Childers: The history of the Cloud Foundry project is, it’s been using Buildpack since nearly the beginning of its inception, originally at VMware, right, before it took it to journey to pivotal and then the CFF. So Buildpacks have demonstrated their value when used with a platform that’s able to implement them effectively, a few times, right? In particular, I’m thinking about the OpenSSL Heartbleed vulnerability. I found that to be a great example of when languages and runtimes don’t embed too many things in their distribution statically, then you’re able to use the Buildpack process to roll out security patches to these really important underlying libraries very quickly.
|
||||
|
||||
Chip Childers: As an example, Kashyap said that the buildpack project with Paketo Buildpacks, they’ve always been keeping up to date with all their critical vulnerabilities or high vulnerabilities from all the languages and frameworks that get pulled together. We had the OpenSSL update rolled out to the whole ecosystem and it managed to percolate through all the platforms that had the CF Buildpacks embedded in them very quickly, like in a matter of days. And it was really smooth. The only hiccup back then was that no JS actually included the OpenSSL library in its own distribution. So I think it was about a month or so after Heartbleed that they split that out and then Buildpacks could be more effective at helping to support some of these underlying libraries.
|
||||
|
||||
**Swapnil Bhartiya: Thanks for explaining that. If I’m not wrong, last year, CNCF also announced a Buildpack project. What is the difference between what CNCF is doing there versus what you guys are trying to do?**
|
||||
|
||||
Kashyap Vidurmudi: That’s a great question and probably the biggest question we’ve been getting asked with this whole launch. So the CNCF Cloud Native Buildpacks project, they built the underlying specification and tooling needed to build a Cloud Native compliant Buildpack. Or the Paketo Buildpacks project is just a set of language family implementations on top of these Cloud Native Buildpack specifications. So we build implementations when we launched the other day, we have Java, node.js, PHP, .NET Core, and probably a couple of others that I’m missing, Buildpack implementations on top of that spec.
|
||||
|
||||
**Swapnil Bhartiya: And why do you call it Paketo Buildpacks, the specific reasons for this naming?**
|
||||
|
||||
Kashyap Vidurmudi: That’s a great question as well. To be completely honest with you, our whole engineering team went through about two different naming exercises just to generate different names for Buildpacks. At a team lunch, a couple of months ago, someone came up with the Paketo, which translates to Greek and… Sorry, it translates to package in Greek. What we really liked about it was Kubernetes translates to pilot and Greek, and we liked that with Paketo translating a package in Greek. We can come off with the association that Paketo packages your apps as container images that any Cloud Native platforms similar to Kubernetes can work as straight. So the name stuck at the end.
|
||||
|
||||
**Swapnil Bhartiya: Talk a bit about the collaboration between Cloud Foundry and VMware for this project.**
|
||||
|
||||
Chip Childers: I want to start probably by saying, the kind of Buildpack project is a Cloud Foundry Foundation project, right? And so what that means is it’s the same engineers and contributors that are working on the traditional Cloud Foundry. Buildpacks are building the Paketo Buildpacks collection, right? So you get all their past experience as a community building and maintaining, and keeping up to date these new Cloud Native Buildpack compliant things. One of the goals of the project team, which I’m sure Kashyap could share a little bit more about as well, is that traditionally the Cloud Foundry Buildpack collection has seen the majority of the effort that was put into maintaining it coming from pivotal.
|
||||
|
||||
There were certainly a lot of casual contributors, but it was something, that pivotal bore the full burden on. And we think that it’s incredibly important that now that the Cloud Native Buildpacks spec can be used in many different platforms. That a lot of participants rally around this because it’s an opportunity to get really high-quality Buildpack code brought into whichever platform you’re using, whether it’s Tecton, or it’s Google Cloud run, or whether it’s the CF [inaudible 00:07:06] distribution of Cloud Foundry. There are going to be a lot of end-users that should be able to amplify the feedback loop back to the project team. And we’re very open to new contributors there.
|
||||
|
||||
**Swapnil Bhartiya: What kind of community are you planning to build around these Paketo Buildpacks and what will be the resources available for the community to build and consume these Buildpacks?**
|
||||
|
||||
Kashyap Vidurmudi: I think just to add on a little bit to what Chip said, the community is super important for us with this whole Paketo Buildpacks launch. I think what we’re looking for ideally is a mix of vendors helping us out similar to what Cloud Foundry Foundation has had in the past, as well as individual contributors. And what’s super exciting to see is we just launched a couple of days ago and we’re already seeing a bunch of people reaching out, and trying out Paketo Buildpacks, and interested in contributing. We’re seeing that maybe people might be interested in helping us develop a Python, Paketo Buildpacks, which is really cool to see. To answer the second part of your question around a marketplace or some ecosystem, I think in the future, that would be super cool to have something like that. In the short term, what we’re doing is we have with this concept of builder images where a builder is effectively a set of Buildpacks, Paketo Buildpacks that are packaged in there. So we ship our builders onto a GCR registry that users can then use to consume our Buildpacks.
|
||||
|
||||
**Swapnil Bhartiya: Is there any specific Buildpacks that will be available or you’ll be focusing on to start with?**
|
||||
|
||||
Kashyap Vidurmudi: Yeah. When we launched the other day, we officially have Java, node.js, .NET Core, PHP, and Nginx Paketo Buildpacks available at the moment. We’re currently just getting started around a Ruby Paketo Buildpacks and looking into publishing some official project-wide roadmap in the future to show what’s coming next.
|
||||
|
||||
Chip Childers: I think that’s another really good opportunity for people to get involved. As you said, there’s been interest organically in helping to add Python as a Buildpack. There’s a very long tail of different languages and frameworks that are used in the enterprise context. And so Paketo Buildpacks was going out the door with a set of Buildpacks that basically solved the majority of enterprise development use cases, right? Python is used very heavily, but it’s a little bit less than Java, right? And so the tail starts to drop a little bit. But there’s a lot of opportunity in those languages and frameworks that the Paketo Buildpacks project team hasn’t created on their own. But those same patterns can be followed for languages that might be maybe less used.
|
||||
|
||||
As the community grows around, not just the Cloud Native Buildpacks spec, right, because anyone can build a Buildpack to that spec. But I think the practices of the Paketo Buildpacks project lend themselves to quality distribution of a Buildpack, right? If you search and get up for Buildpacks, even if you’re just looking at the past version of the way Buildpacks work, you find thousands of them, right? But some of them are stale, some of them are, they have work. And I think the more important than exactly which Buildpacks are offered today is that the Paketo Buildpacks project is an opportunity for people to come together around the discipline of building quality Buildpacks and then maintaining them over time.
|
||||
|
||||
Kashyap Vidurmudi: Yeah, exactly. That’s a really good point. And I think that over the next coming weeks to months, we’re really focused on improving a lot of our documentation to help enable things like this. We have a couple of tutorials right now just to help users create a Paketo style Buildpack and lots of tools and things like that out there. So my end goal and just sure Chip agrees with this, which is, I’d love to see a user just coming in with very little Buildpack experience and be able to build, say, a Rust Cloud Native Buildpack or something like that very simply and easily and support that. And that’s the end goal of where we want to go in terms of enabling the community to build Buildpacks easily.
|
||||
|
||||
**Swapnil Bhartiya: So what happens to the existing Buildpacks that people are already using?**
|
||||
|
||||
Kashyap Vidurmudi: For Cloud Foundry Buildpacks, we’re going to continue providing support for CF workloads into the foreseeable future. So what we did is we built a concept of a compatibility layer on top of every one of our Paketo Buildpacks, which allow us to ship a Cloud Foundry compatible Cloud Native Buildpack. And that enables your CF workflows to continue to work with Paketo Buildpacks.
|
||||
|
||||
Chip Childers: I think one of the things to understand, and this is where it gets a little bit confusing, right? Buildpacks as a concept has a fairly long history. So it started at Heroku. CF was emulating Heroku, right? It was the open source alternative to Heroku and it implemented Buildpacks in order to have that support. And for a while, they were largely compatible, right? You could take a Heroku Buildpack and you could use that in a Cloud Foundry context or you could do the reverse. And so that worked for a while. The two platforms, right, Cloud Foundry and opensource community. And then Heroku as a product or a platform as a service, that’s all proprietary, they started to diverge, right? So the compatibility within the ecosystem started to break down.
|
||||
|
||||
When the CNCF Cloud Native Buildpacks project kicked off, to me that was actually one of the most important moments in the platform as a service space in a number of years. Because it represented a reconvergence of streams of work and sets of experiences with different end-users that made a ton of sense for everyone. But what that means though, is that the CMB spec is, it’s a new way to build Buildpacks, right? So all that historical work for the CF community building that shim is important, but it’s really critical to understand that a Cloud Native Buildpack, compliant Buildpack is different from a traditional Heroku or Cloud Foundry, older version Buildpack. They’re implemented differently. And so it’s a new generation of them. And that’s where a new ecosystem because there are multiple platforms that don’t support their use, is really going to kick in here.
|
||||
|
||||
**Swapnil Bhartiya: Kashyap, you mentioned there’ll be a lot of resources documentation that would be coming up. What are the resources that are available at this moment that people can either read or go to that to get more aware of the project at the same time, how they can get involved with the project?**
|
||||
|
||||
Kashyap Vidurmudi: Yeah. So right now we have a couple of tutorials out there just around how to get started with Paketo Buildpacks as well as how to go ahead and create your own Paketo Buildpacks. In terms of getting started and helping out and getting involved, I think the best way to get started right now is to join us on Slack, our Slack is Slack.paketo, P-A-K-E-T-O.io, or visit our website and go through the content. The website is P-A-K-E-T-O.io.
|
||||
|
||||
**Swapnil Bhartiya: Chip and Kashyap, thank you so much for taking time out of your schedule and talking to us today about this project. Good luck with that project and thank you once again.**
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://www.linux.com/audience/developers/what-do-paketo-buildpacks-mean-for-developers-and-operators/
|
||||
|
||||
作者:[Swapnil Bhartiya][a]
|
||||
选题:[lujun9972][b]
|
||||
译者:[译者ID](https://github.com/译者ID)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://www.linux.com/author/swapnil/
|
||||
[b]: https://github.com/lujun9972
|
||||
[1]: https://paketo.io/
|
||||
[2]: https://www.tfir.io/author/arnieswap/
|
@ -1,204 +0,0 @@
|
||||
[#]: collector: (lujun9972)
|
||||
[#]: translator: (011011100010110101101111)
|
||||
[#]: reviewer: ( )
|
||||
[#]: publisher: ( )
|
||||
[#]: url: ( )
|
||||
[#]: subject: (How to install Python on Windows)
|
||||
[#]: via: (https://opensource.com/article/19/8/how-install-python-windows)
|
||||
[#]: author: (Seth Kenlon https://opensource.com/users/sethhttps://opensource.com/users/greg-p)
|
||||
|
||||
如何在Windows上安装Python
|
||||
======
|
||||
Install Python, run an IDE, and start coding right from your Microsoft
|
||||
Windows desktop.
|
||||
> 安装Python,启动IDE,然后你就可以在Windows系统下进行编程了。
|
||||
![Hands programming][1]
|
||||
|
||||
So you want to learn to program? One of the most common languages to start with is [Python][2], popular for its unique blend of [object-oriented][3] structure and simple syntax. Python is also an _interpreted_ _language_, meaning you don't need to learn how to compile code into machine language: Python does that for you, allowing you to test your programs sometimes instantly and, in a way, while you write your code.
|
||||
|
||||
Just because Python is easy to learn doesn't mean you should underestimate its potential power. Python is used by [movie][4] [studios][5], financial institutions, IT houses, video game studios, makers, hobbyists, [artists][6], teachers, and many others.
|
||||
|
||||
On the other hand, Python is also a serious programming language, and learning it takes dedication and practice. Then again, you don't have to commit to anything just yet. You can install and try Python on nearly any computing platform, so if you're on Windows, this article is for you.
|
||||
|
||||
If you want to try Python on a completely open source operating system, you can [install Linux][7] and then [try Python][8].
|
||||
|
||||
### Get Python
|
||||
|
||||
Python is available from its website, [Python.org][9]. Once there, hover your mouse over the **Downloads** menu, then over the **Windows** option, and then click the button to download the latest release.
|
||||
|
||||
![Downloading Python on Windows][10]
|
||||
|
||||
Alternatively, you can click the **Downloads** menu button and select a specific version from the downloads page.
|
||||
|
||||
### Install Python
|
||||
|
||||
Once the package is downloaded, open it to start the installer.
|
||||
|
||||
It is safe to accept the default install location, and it's vital to add Python to PATH. If you don't add Python to your PATH, then Python applications won't know where to find Python (which they require in order to run). This is _not_ selected by default, so activate it at the bottom of the install window before continuing!
|
||||
|
||||
![Select "Add Python 3 to PATH"][11]
|
||||
|
||||
Before Windows allows you to install an application from a publisher other than Microsoft, you must give your approval. Click the **Yes** button when prompted by the **User Account Control** system.
|
||||
|
||||
![Windows UAC][12]
|
||||
|
||||
Wait patiently for Windows to distribute the files from the Python package into the appropriate locations, and when it's finished, you're done installing Python.
|
||||
|
||||
Time to play.
|
||||
|
||||
### Install an IDE
|
||||
|
||||
To write programs in Python, all you really need is a text editor, but it's convenient to have an integrated development environment (IDE). An IDE integrates a text editor with some friendly and helpful Python features. IDLE 3 and NINJA-IDE are two options to consider.
|
||||
|
||||
#### IDLE 3
|
||||
|
||||
Python comes with an IDE called IDLE. You can write code in any text editor, but using an IDE provides you with keyword highlighting to help detect typos, a **Run** button to test code quickly and easily, and other code-specific features that a plain text editor like [Notepad++][13] normally doesn't have.
|
||||
|
||||
To start IDLE, click the **Start** (or **Window**) menu and type **python** for matches. You may find a few matches, since Python provides more than one interface, so make sure you launch IDLE.
|
||||
|
||||
![IDLE 3 IDE][14]
|
||||
|
||||
If you don't see Python in the Start menu, launch the Windows command prompt by typing **cmd** in the Start menu, then type:
|
||||
|
||||
|
||||
```
|
||||
`C:\Windows\py.exe`
|
||||
```
|
||||
|
||||
If that doesn't work, try reinstalling Python. Be sure to select **Add Python to PATH** in the install wizard. Refer to the [Python docs][15] for detailed instructions.
|
||||
|
||||
#### Ninja-IDE
|
||||
|
||||
If you already have some coding experience and IDLE seems too simple for you, try [Ninja-IDE][16]. Ninja-IDE is an excellent Python IDE. It has keyword highlighting to help detect typos, quotation and parenthesis completion to avoid syntax errors, line numbers (helpful when debugging), indentation markers, and a **Run** button to test code quickly and easily.
|
||||
|
||||
![Ninja-IDE][17]
|
||||
|
||||
To install it, visit the Ninja-IDE website and [download the Windows installer][18]. The process is the same as with Python: start the installer, allow Windows to install a non-Microsoft application, and wait for the installer to finish.
|
||||
|
||||
Once Ninja-IDE is installed, double-click the Ninja-IDE icon on your desktop or select it from the Start menu.
|
||||
|
||||
### Tell Python what to do
|
||||
|
||||
Keywords tell Python what you want it to do. In either IDLE or Ninja-IDE, go to the File menu and create a new file.
|
||||
|
||||
Ninja users: Do not create a new project, just a new file.
|
||||
|
||||
In your new, empty file, type this into IDLE or Ninja-IDE:
|
||||
|
||||
|
||||
```
|
||||
`print("Hello world.")`
|
||||
```
|
||||
|
||||
* If you are using IDLE, go to the Run menu and select the Run Module option.
|
||||
* If you are using Ninja, click the Run File button in the left button bar.
|
||||
|
||||
|
||||
|
||||
![Running code in Ninja-IDE][19]
|
||||
|
||||
Any time you run code, your IDE prompts you to save the file you're working on. Do that before continuing.
|
||||
|
||||
The keyword **print** tells Python to print out whatever text you give it in parentheses and quotes.
|
||||
|
||||
That's not very exciting, though. At its core, Python has access to only basic keywords like **print** and **help**, basic math functions, and so on.
|
||||
|
||||
Use the **import** keyword to load more keywords. Start a new file in IDLE or Ninja and name it **pen.py**.
|
||||
|
||||
**Warning**: Do not call your file **turtle.py**, because **turtle.py** is the name of the file that contains the turtle program you are controlling. Naming your file **turtle.py** confuses Python because it thinks you want to import your own file.
|
||||
|
||||
Type this code into your file and run it:
|
||||
|
||||
|
||||
```
|
||||
`import turtle`
|
||||
```
|
||||
|
||||
[Turtle][20] is a fun module to use. Add this code to your file:
|
||||
|
||||
|
||||
```
|
||||
turtle.begin_fill()
|
||||
turtle.forward(100)
|
||||
turtle.left(90)
|
||||
turtle.forward(100)
|
||||
turtle.left(90)
|
||||
turtle.forward(100)
|
||||
turtle.left(90)
|
||||
turtle.forward(100)
|
||||
turtle.end_fill()
|
||||
```
|
||||
|
||||
See what shapes you can draw with the turtle module.
|
||||
|
||||
To clear your turtle drawing area, use the **turtle.clear()** keyword. What do you think the keyword **turtle.color("blue")** does?
|
||||
|
||||
Try more complex code:
|
||||
|
||||
|
||||
```
|
||||
import turtle as t
|
||||
import time
|
||||
|
||||
t.color("blue")
|
||||
t.begin_fill()
|
||||
|
||||
counter = 0
|
||||
|
||||
while counter < 4:
|
||||
t.forward(100)
|
||||
t.left(90)
|
||||
counter = counter+1
|
||||
|
||||
t.end_fill()
|
||||
time.sleep(2)
|
||||
```
|
||||
|
||||
As a challenge, try changing your script to get this result:
|
||||
|
||||
![Example Python turtle output][21]
|
||||
|
||||
Once you complete that script, you're ready to move on to more exciting modules. A good place to start is this [introductory dice game][22].
|
||||
|
||||
### Stay Pythonic
|
||||
|
||||
Python is a fun language with modules for practically anything you can think to do with it. As you can see, it's easy to get started with Python, and as long as you're patient with yourself, you may find yourself understanding and writing Python code with the same fluidity as you write your native language. Work through some [Python articles][23] here on Opensource.com, try scripting some small tasks for yourself, and see where Python takes you. To really integrate Python with your daily workflow, you might even try Linux, which is natively scriptable in ways no other operating system is. You might find yourself, given enough time, using the applications you create!
|
||||
|
||||
Good luck, and stay Pythonic.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://opensource.com/article/19/8/how-install-python-windows
|
||||
|
||||
作者:[Seth Kenlon][a]
|
||||
选题:[lujun9972][b]
|
||||
译者:[译者ID](https://github.com/译者ID)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://opensource.com/users/sethhttps://opensource.com/users/greg-p
|
||||
[b]: https://github.com/lujun9972
|
||||
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/programming-code-keyboard-laptop.png?itok=pGfEfu2S (Hands programming)
|
||||
[2]: https://www.python.org/
|
||||
[3]: https://opensource.com/article/19/7/get-modular-python-classes
|
||||
[4]: https://github.com/edniemeyer/weta_python_db
|
||||
[5]: https://www.python.org/about/success/ilm/
|
||||
[6]: https://opensource.com/article/19/7/rgb-cube-python-scribus
|
||||
[7]: https://opensource.com/article/19/7/ways-get-started-linux
|
||||
[8]: https://opensource.com/article/17/10/python-101
|
||||
[9]: https://www.python.org/downloads/
|
||||
[10]: https://opensource.com/sites/default/files/uploads/win-python-install.jpg (Downloading Python on Windows)
|
||||
[11]: https://opensource.com/sites/default/files/uploads/win-python-path.jpg (Select "Add Python 3 to PATH")
|
||||
[12]: https://opensource.com/sites/default/files/uploads/win-python-publisher.jpg (Windows UAC)
|
||||
[13]: https://notepad-plus-plus.org/
|
||||
[14]: https://opensource.com/sites/default/files/uploads/idle3.png (IDLE 3 IDE)
|
||||
[15]: http://docs.python.org/3/using/windows.html
|
||||
[16]: http://ninja-ide.org/
|
||||
[17]: https://opensource.com/sites/default/files/uploads/win-python-ninja.jpg (Ninja-IDE)
|
||||
[18]: http://ninja-ide.org/downloads/
|
||||
[19]: https://opensource.com/sites/default/files/uploads/ninja_run.png (Running code in Ninja-IDE)
|
||||
[20]: https://opensource.com/life/15/8/python-turtle-graphics
|
||||
[21]: https://opensource.com/sites/default/files/uploads/win-python-idle-turtle.jpg (Example Python turtle output)
|
||||
[22]: https://opensource.com/article/17/10/python-101#python-101-dice-game
|
||||
[23]: https://opensource.com/sitewide-search?search_api_views_fulltext=Python
|
@ -0,0 +1,114 @@
|
||||
[#]: collector: (lujun9972)
|
||||
[#]: translator: ( )
|
||||
[#]: reviewer: ( )
|
||||
[#]: publisher: ( )
|
||||
[#]: url: ( )
|
||||
[#]: subject: (How to dump the GOSSAFUNC graph for a method)
|
||||
[#]: via: (https://dave.cheney.net/2020/06/19/how-to-dump-the-gossafunc-graph-for-a-method)
|
||||
[#]: author: (Dave Cheney https://dave.cheney.net/author/davecheney)
|
||||
|
||||
How to dump the GOSSAFUNC graph for a method
|
||||
======
|
||||
|
||||
The Go compiler’s SSA backend contains a facility to produce HTML debugging output of the compilation phases. This post covers how to print the SSA output for function _and_ methods.
|
||||
|
||||
Let’s start with a sample program which contains a function, a value method, and a pointer method:
|
||||
|
||||
```
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Numbers struct {
|
||||
vals []int
|
||||
}
|
||||
|
||||
func (n *Numbers) Add(v int) {
|
||||
n.vals = append(n.vals, v)
|
||||
}
|
||||
|
||||
func (n Numbers) Average() float64 {
|
||||
sum := 0.0
|
||||
for _, num := range n.vals {
|
||||
sum += float64(num)
|
||||
}
|
||||
return sum / float64(len(n.vals))
|
||||
}
|
||||
|
||||
|
||||
func main() {
|
||||
var numbers Numbers
|
||||
numbers.Add(200)
|
||||
numbers.Add(43)
|
||||
numbers.Add(-6)
|
||||
fmt.Println(numbers.Average())
|
||||
}
|
||||
```
|
||||
|
||||
Control of the SSA debugging output is via the `GOSSAFUNC` environment variable. This variable takes the name of the function to dump. This is _not_ the functions fully qualified name. For `func main` above the name of the function is `main` _not_ `main.main`.
|
||||
|
||||
```
|
||||
% env GOSSAFUNC=main go build
|
||||
runtime
|
||||
dumped SSA to ../../go/src/runtime/ssa.html
|
||||
t
|
||||
dumped SSA to ./ssa.html
|
||||
```
|
||||
|
||||
In this example `GOSSAFUNC=main` matched both `main.main` and a function called `runtime.main`.[1][1] This is a little unfortunate, but in practice probably not a big deal as, if you’re performance tuning your code, it won’t be in a giant spaghetti blob in `func main`.
|
||||
|
||||
What is more likely is your code will be in a _method_, so you’ve probably landed on this post looking for the correct incantation to dump the SSA output for a method.
|
||||
|
||||
To print the SSA debug for the pointer method `func (n *Numbers) Add`, the equivalent function name is`(*Numbers).Add`:[2][2]
|
||||
|
||||
```
|
||||
% env "GOSSAFUNC=(*Numbers).Add" go build
|
||||
t
|
||||
dumped SSA to ./ssa.html
|
||||
```
|
||||
|
||||
To print the SSA debug for a value method `func (n Numbers) Average`, the equivalent function name is `(*Numbers).Average` _even though this is a value method_:
|
||||
|
||||
```
|
||||
% env "GOSSAFUNC=(*Numbers).Average" go build
|
||||
t
|
||||
dumped SSA to ./ssa.html
|
||||
```
|
||||
|
||||
1. If you didn’t build Go from source then the path to the `runtime` package may be read only and you might receive an error. Please don’t use the `sudo` hammer to fix this.[][3]
|
||||
2. Please pay attention to the shell quoting.[][4]
|
||||
|
||||
|
||||
|
||||
### Related posts:
|
||||
|
||||
1. [Accidental method value][5]
|
||||
2. [Never edit a method, always rewrite it][6]
|
||||
3. [How to find out which Go version built your binary][7]
|
||||
4. [Declaration scopes in Go][8]
|
||||
|
||||
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://dave.cheney.net/2020/06/19/how-to-dump-the-gossafunc-graph-for-a-method
|
||||
|
||||
作者:[Dave Cheney][a]
|
||||
选题:[lujun9972][b]
|
||||
译者:[译者ID](https://github.com/译者ID)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://dave.cheney.net/author/davecheney
|
||||
[b]: https://github.com/lujun9972
|
||||
[1]: tmp.kLSHpQXzhr#easy-footnote-bottom-1-4188 (If you didn’t build Go from source then the path to the <code>runtime</code> package may be read only and you might receive an error. Please don’t use the <code>sudo</code> hammer to fix this.)
|
||||
[2]: tmp.kLSHpQXzhr#easy-footnote-bottom-2-4188 (Please pay attention to the shell quoting.)
|
||||
[3]: tmp.kLSHpQXzhr#easy-footnote-1-4188
|
||||
[4]: tmp.kLSHpQXzhr#easy-footnote-2-4188
|
||||
[5]: https://dave.cheney.net/2014/05/19/accidental-method-value (Accidental method value)
|
||||
[6]: https://dave.cheney.net/2017/11/30/never-edit-a-method-always-rewrite-it (Never edit a method, always rewrite it)
|
||||
[7]: https://dave.cheney.net/2017/06/20/how-to-find-out-which-go-version-built-your-binary (How to find out which Go version built your binary)
|
||||
[8]: https://dave.cheney.net/2016/12/15/declaration-scopes-in-go (Declaration scopes in Go)
|
@ -0,0 +1,338 @@
|
||||
[#]: collector: (lujun9972)
|
||||
[#]: translator: ( )
|
||||
[#]: reviewer: ( )
|
||||
[#]: publisher: ( )
|
||||
[#]: url: ( )
|
||||
[#]: subject: (How to prepare to write your first Mycroft AI skill using Python)
|
||||
[#]: via: (https://opensource.com/article/20/6/mycroft-voice-assistant-skill)
|
||||
[#]: author: (Steve Ovens https://opensource.com/users/stratusss)
|
||||
|
||||
How to prepare to write your first Mycroft AI skill using Python
|
||||
======
|
||||
Planning is the essential first step in writing a skill and teaching
|
||||
Mycroft how to do what you want it to do.
|
||||
![A person looking at a phone][1]
|
||||
|
||||
With the recent worldwide pandemic and stay-at-home orders, I have been looking for things to do to replace some of my usual activities. I started to update my home electronics setup and, as part of that, to delve into home automation. Some of my friends use Amazon's Alexa to turn lights on and off in their house, and that is appealing on some level. However, I am a privacy-conscious individual, and I was never really comfortable with devices from Google or Amazon listening to my family all the time (I'll ignore cellphones for the sake of this conversation). I have known about the open source voice assistant [Mycroft][2] for about four years, but due to early struggles with the project, I'd never investigated it too closely. The project has come a very long way since I first stumbled across it, and it checks a lot of boxes for me:
|
||||
|
||||
* Self-hosted
|
||||
* Easy onboarding (via Python)
|
||||
* Open source
|
||||
* Privacy-conscious
|
||||
* Interactive chat channel
|
||||
|
||||
|
||||
|
||||
In the [first article][3] in this series, I introduced Mycroft, and in the [second article][3], I touched upon the concept of skills in artificial intelligence. In its most basic form, a skill is a block of code that is executed to achieve the result desired for an intent. Intents attempt to determine _what_ you want, and a skill is the way Mycroft responds. If you can think of an outcome, there is probably a way to create a skill that makes it happen.
|
||||
|
||||
At their heart, Mycroft skills are just Python programs. Generically, they have three or four sections:
|
||||
|
||||
1. The **import** section is where you load any Python modules required to accomplish the task.
|
||||
2. An optional **function** section contains snippets of code that are defined outside of the main class section.
|
||||
3. The **class** section is where all the magic happens. A class should always take the `MycroftSkill` as an argument.
|
||||
4. The **create_skill()** section is what Mycroft uses to load your skill.
|
||||
|
||||
|
||||
|
||||
When I write a skill, I often start by writing a standard Python file to ensure my code does what I think it does. I do this mainly because the workflow that I am used to, including debugging tools, exists outside of the Mycroft ecosystem. Therefore, if I need to step through my code, I find it much more familiar to use my IDE ([PyCharm][4]) and its built-in tools, but this is a personal preference.
|
||||
|
||||
All the code for this project can be found in my [GitLab repo][5].
|
||||
|
||||
### About intent parsers
|
||||
|
||||
The skill in this project uses both the [Padatious][6] and [Adapt][7] intent parsers, which I described in my [previous][3] article. Why? First of all, this tutorial is meant to provide a concrete example of some of the features you might want to consider using in your own skill. Second, Padatious intents are very straightforward but do not support [regular expressions][8], while Adapt puts regex to good use. Also, Padatious intents aren't context-aware, which means that, while you could prompt the user for a response and then parse it following some decision-tree matrix, you might be better off using the Adapt intent parser with Mycroft's built-in context handler. Note that, by default, Mycroft assumes you are using the Padatious intent handler. Finally, it's good to note that Adapt is a keyword intent parser. This can make complex parsing cumbersome if you are not a regex ninja. (I am not.)
|
||||
|
||||
## Implement the 3 T's
|
||||
|
||||
Before you start writing a skill, consider the 3 T's: _Think things through_! Similar to when you're writing an outline for an essay, when you're starting to develop a skill, write down what you want your skill to do.
|
||||
|
||||
This tutorial will step through writing a Mycroft skill to add items to the [OurGroceries][9] app (which I am not affiliated with). In truth, this skill was my wife's idea. She wanted an application she could use on her phone to manage her shopping lists. We tried almost a dozen apps to try to meet our individual needs—I needed an API or a way to easily interact with the backend, and she had a giant list of criteria, one of the most important was that it is easy to use from her phone. After she made her list of Must-haves, Nice-to-haves, and Wish-list items, we settled on OurGroceries. It does not have an API, but it does have a way to interact with it through JSON. There is even a [handy library][10] called `py-our-groceries` in PyPI (which I have contributed some small amount to).
|
||||
|
||||
Once I had an objective and a target platform, I started to outline what the skill needed to do:
|
||||
|
||||
1. Login/authenticate
|
||||
2. Get a list of the current grocery lists
|
||||
3. Add item to a specific grocery list
|
||||
4. Add item to a category under a specific list
|
||||
5. Add a category (since OurGroceries allows items to be placed in categories)
|
||||
|
||||
|
||||
|
||||
With this in mind, I started to sketch out the required Python. Here is what I came up with.
|
||||
|
||||
## Create the Python sketch
|
||||
|
||||
By reading the examples for the `py-our-groceries` library, I figured out I needed to import just two things: `asyncio` and `ourgroceries`.
|
||||
|
||||
Simple enough. Next, I knew that I needed to authenticate with `username` and `password`, and I knew what tasks the program needed to do. So my sketch ended up looking like this:
|
||||
|
||||
|
||||
```
|
||||
import asyncio
|
||||
from ourgroceries import OurGroceries
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
|
||||
USERNAME = ""
|
||||
PASSWORD = ""
|
||||
OG = OurGroceries(USERNAME, PASSWORD)
|
||||
|
||||
def fetch_list_and_categories():
|
||||
pass
|
||||
|
||||
def return_category_id():
|
||||
pass
|
||||
|
||||
def add_to_my_list():
|
||||
pass
|
||||
|
||||
def add_category():
|
||||
pass
|
||||
```
|
||||
|
||||
I won't go into the full details of what makes this sketch tick, as that is outside the scope of this series. However, if you want, you can [view the working outline][11] in its entirety.
|
||||
|
||||
Before you can begin programming, you need to have your username, password, and a list ID. The username and password are obvious. The list ID can be retrieved from the URL after clicking on the link, or more programmatically, you can use the Developer Tools for your browser of choice and inspect the objects. Here is what the Developer Tools looks like [in Firefox][12]:
|
||||
|
||||
![CC BY-SA Steve Ovens][13]
|
||||
|
||||
Once you have a list ID, log into OurGroceries and get a cookie. To do this, create an OurGroceries _object_ and then pass it into `asyncio`. While you are at it, you might as well define your list ID, as well:
|
||||
|
||||
|
||||
```
|
||||
OG = OurGroceries(USERNAME, PASSWORD)
|
||||
asyncio.run(OG.login())
|
||||
MY_LIST_ID = "a1kD7kvcMPnzr9del8XMFc"
|
||||
```
|
||||
|
||||
For the purposes of this project, you need to define two object types to help organize your code: `groceries` and `categories`. The `fetch_list_and_categories` method is pretty straightforward:
|
||||
|
||||
|
||||
```
|
||||
def fetch_list_and_categories(object_type=None):
|
||||
if object_type == "groceries":
|
||||
list_to_return = asyncio.run(OG.get_list_items(list_id=MY_LIST_ID))
|
||||
elif object_type == "categories":
|
||||
list_to_return = asyncio.run(OG.get_category_items())
|
||||
else:
|
||||
list_to_return = None
|
||||
return (list_to_return)
|
||||
```
|
||||
|
||||
OurGroceries allows you to add more than one category or item with the same name. For example, if you already have "Meat" on your list and you add it again, you will see a category called "Meat (2)" (this number increments whenever you create a category with the same name). For us, this was undesirable behavior. We also wanted to avoid duplication as much as possible, so I made a rudimentary attempt at detecting plurals; for example, my code checks for both "Meat" and "Meats." I am sure there is a more intelligent way of performing these checks, but this example highlights some of the things you may want to think about as you progress. For brevity, I will omit these checks, so the `return_category_id` method looks something like this:
|
||||
|
||||
|
||||
```
|
||||
def return_category_id(category_to_search_for, all_categories):
|
||||
category_to_search_for_lower = category_to_search_for.lower()
|
||||
category_id = None
|
||||
if len(all_categories['list']['items']) is not 0:
|
||||
for category_heading in all_categories['list']['items']:
|
||||
# Split the heading because if there is already a duplicate it
|
||||
# presents as "{{item}} (2)"
|
||||
category_heading_lowered = category_heading['value'].lower().split()[0]
|
||||
if category_to_search_for_lower == category_heading_lowered:
|
||||
category_id = category_heading['id']
|
||||
break
|
||||
return(category_id)
|
||||
```
|
||||
|
||||
To add an item to the list, you want to:
|
||||
|
||||
1. Check that the item does not already exist
|
||||
2. Obtain the category ID
|
||||
3. Add the item to the list under a specific category (if specified)
|
||||
|
||||
|
||||
|
||||
The `add_to_my_list` method ends up something like this:
|
||||
|
||||
|
||||
```
|
||||
def add_to_my_list(full_list, item_name, all_categories, category="uncategorized"):
|
||||
# check to make sure the object doesn't exist
|
||||
# The groceries live in my_full_list['list']['items']
|
||||
# Start with the assumption that the food does not exist
|
||||
food_exists = False
|
||||
toggle_crossed_off = False
|
||||
category_lowered = category.lower()
|
||||
for food_item in full_list['list']['items']:
|
||||
if item_name in food_item['value']:
|
||||
print("Already exists")
|
||||
food_exists = True
|
||||
if not food_exists:
|
||||
category_id = return_category_id(category_lowered, all_categories)
|
||||
asyncio.run(OG.add_item_to_list(MY_LIST_ID, item_name, category_id))
|
||||
print("Added item")
|
||||
```
|
||||
|
||||
Finally, `add_category` runs the `asyncio` command to create a category if it does not already exist:
|
||||
|
||||
|
||||
```
|
||||
def add_category(category_name, all_categories):
|
||||
category_id = return_category_id(category_name, all_categories)
|
||||
if category_id is None:
|
||||
asyncio.run(OG.create_category(category_name))
|
||||
refresh_lists()
|
||||
print("Added Category")
|
||||
else:
|
||||
print("Category already exists")
|
||||
```
|
||||
|
||||
You should now be able to test your sketch to make sure everything in each function works. Once you are satisfied with the sketch, you can move on to thinking about how to implement it in a Mycroft skill.
|
||||
|
||||
## Plan the Mycroft skill
|
||||
|
||||
You can apply the same principles you used to sketch out your Python to developing a Mycroft skill. The [official documentation][14] recommends using an interactive helper program called the Mycroft Skills Kit to set up a skill. `mycroft-msk create` asks you to:
|
||||
|
||||
* Name your skill
|
||||
* Enter some phrases commonly used to trigger your skill
|
||||
* Identify what dialog Mycroft should respond with
|
||||
* Create a skill description
|
||||
* Pick an icon from `fontawesome.com/cheatsheet`
|
||||
* Pick a color from `mycroft.ai/colors` or `color-hex.com`
|
||||
* Define a category (or categories) where the skill belongs
|
||||
* Specify the code's license
|
||||
* State whether the skill will have dependencies
|
||||
* Indicate whether you want to create a GitHub repo
|
||||
|
||||
|
||||
|
||||
Here is a demonstration of how `mycroft-msk create` works:
|
||||
|
||||
![mycroft-msk create working][15]
|
||||
|
||||
(Steve Ovens, [CC BY-SA 4.0][16])
|
||||
|
||||
After you answer these questions, Mycroft creates the following structure under `mycroft-core/skills/<skill name>`:
|
||||
|
||||
|
||||
```
|
||||
├── __init__.py
|
||||
├── locale
|
||||
│ └── en-us
|
||||
│ ├── ourgroceries.dialog
|
||||
│ └── ourgroceries.intent
|
||||
├── __pycache__
|
||||
│ └── __init__.cpython-35.pyc
|
||||
├── README.md
|
||||
├── settings.json
|
||||
└── settingsmeta.yaml
|
||||
```
|
||||
|
||||
You can ignore most of these files for now. I prefer to make sure my code is working before trying to get into Mycroft-specific troubleshooting. This way, if things go wrong later, you know it is related to how your Mycroft skill is constructed and not the code itself. As with the Python sketch, take a look at the outline that Mycroft created in `__init__.py`.
|
||||
|
||||
All Mycroft skills should have an `__init__.py`. By convention, all code should go in this file, although if you are a skilled Python developer and know how this file works, you could choose to break your code out.
|
||||
|
||||
Inside the file Mycroft created, you can see:
|
||||
|
||||
|
||||
```
|
||||
from mycroft import MycroftSkill, intent_file_handler
|
||||
|
||||
class OurGroceries(MycroftSkill):
|
||||
def __init__(self):
|
||||
MycroftSkill.__init__(self)
|
||||
|
||||
@intent_file_handler('ourgroceries.intent')
|
||||
def handle_test(self, message):
|
||||
self.speak_dialog('ourgroceries')
|
||||
|
||||
def create_skill():
|
||||
return OurGroceries()
|
||||
```
|
||||
|
||||
In theory, this code will execute based on the trigger(s) you create during the `msk create` process. Mycroft first tries to find a file with the `.dialog` file extension that matches the argument passed to `selfspeak_dialog()`. In the example above, Mycroft will look for a file called `ourgroceries.dialog` and then say one of the phrases it finds there. Failing that, it will say the name of the file. I'll get more into this in a follow-up article about responses. If you want to try this process, feel free to explore the various input and output phrases you can come up with during skill creation.
|
||||
|
||||
While the script is a great starting point, I prefer to think through the `__init__.py` on my own. As mentioned earlier, this skill will use both the Adapt and Padatious intent handlers, and I also want to demonstrate [conversational context handling][17] (which I'll get deeper into in the next article). So start by importing them:
|
||||
|
||||
|
||||
```
|
||||
from mycroft import intent_file_handler, MycroftSkill, intent_handler
|
||||
from mycroft.skills.context import adds_context, removes_context
|
||||
```
|
||||
|
||||
In case you are wondering, the order you specify your import statements does not matter in Python. After the imports are done, look at the class structure. If you want to learn more about classes and their uses, [Real Python][18] has a great primer on the subject.
|
||||
|
||||
As above, start by mocking up your code with its intended functionality. This section uses the same goals as the Python sketch, so go ahead and plug some of that in, this time adding some comments to help guide you:
|
||||
|
||||
|
||||
```
|
||||
class OurGroceriesSkill(MycroftSkill):
|
||||
def __init__(self):
|
||||
MycroftSkill.__init__(self)
|
||||
|
||||
# Mycroft should call this function directly when the user
|
||||
# asks to create a new item
|
||||
def create_item_on_list(self, message):
|
||||
pass
|
||||
|
||||
# Mycroft should also call this function directly
|
||||
def create_shopping_list(self, message):
|
||||
pass
|
||||
|
||||
# This is not called directly, but instead should be triggered
|
||||
# as part of context aware decisions
|
||||
def handle_dont_create_anyways_context(self):
|
||||
pass
|
||||
|
||||
# This function is also part of the context aware decision tree
|
||||
def handle_create_anyways_context(self):
|
||||
pass
|
||||
|
||||
|
||||
def stop(self):
|
||||
pass
|
||||
```
|
||||
|
||||
### The `__init__` and `initialize` methods
|
||||
|
||||
A skill has a few "special" functions that you should know about. The `__init__(self)` method is called when the skill is first instantiated. In Python IDEs, variables that are declared outside of the `__init__` section will often cause warnings. Therefore, they are often used to declare variables or perform setup actions. However, while you can declare variables intended to match the skills settings file (more on this later), you cannot use the Mycroft methods (such as `self.settings.get)` to retrieve the values. It is generally not appropriate to attempt to make connections to the outside world from `__init__`. Also, the `__init__` function is considered optional within Mycroft. Most skills opt to have one, and it is considered the "Pythonic" way of doing things.
|
||||
|
||||
The `initialize` method is called after the skill is fully constructed and registered with the system. It is used to perform any final setup for the skill, including accessing skill settings. It is optional, however, and I opted to create a function that gets the authentication information. I called it `_create_initial_grocery_connection`, if you are curious and want to look ahead. I will revisit these two special functions in the next article when I start walking through creating the skill code.
|
||||
|
||||
Finally, there is a special function called `stop()`, which I didn't use. The stop method is called anytime a user says, "stop." If you have a long-running process or audio playback, this method is useful.
|
||||
|
||||
## Wrapping up
|
||||
|
||||
So you now have the outline of what you want to accomplish. This will definitely grow over time. As you develop your skill, you will discover new functionality that your skill will require to work optimally.
|
||||
|
||||
Next time, I will talk about the types of intents you will use, how to set them up, and how to deal with regular expressions. I'll also explore the idea of [conversational contexts][17], which are used for getting feedback from the user.
|
||||
|
||||
Do you have any comments, questions, or concerns? Leave a comment, visit me on Twitter [@linuxovens][19], or stop by [Mycroft skills chat channels][20].
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://opensource.com/article/20/6/mycroft-voice-assistant-skill
|
||||
|
||||
作者:[Steve Ovens][a]
|
||||
选题:[lujun9972][b]
|
||||
译者:[译者ID](https://github.com/译者ID)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://opensource.com/users/stratusss
|
||||
[b]: https://github.com/lujun9972
|
||||
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/idea_innovation_mobile_phone.png?itok=RqVtvxkd (A person looking at a phone)
|
||||
[2]: https://mycroft.ai/
|
||||
[3]: https://opensource.com/article/20/6/open-source-voice-assistant
|
||||
[4]: https://www.jetbrains.com/pycharm/
|
||||
[5]: https://gitlab.com/stratus-ss/mycroft-ourgroceries-skill
|
||||
[6]: https://mycroft-ai.gitbook.io/docs/skill-development/user-interaction/intents/padatious-intents
|
||||
[7]: https://mycroft-ai.gitbook.io/docs/skill-development/user-interaction/intents/adapt-intents
|
||||
[8]: https://www.computerhope.com/jargon/r/regex.htm
|
||||
[9]: https://www.ourgroceries.com/overview
|
||||
[10]: https://github.com/ljmerza/py-our-groceries
|
||||
[11]: https://gitlab.com/stratus-ss/mycroft-ourgroceries-skill/-/blob/master/talk_to_ourgroceries.py
|
||||
[12]: https://developer.mozilla.org/en-US/docs/Tools
|
||||
[13]: https://opensource.com/sites/default/files/resize/ourgroceries_ids-675x201.jpg (Getting an ID)
|
||||
[14]: https://mycroft-ai.gitbook.io/docs/skill-development/introduction/your-first-skill
|
||||
[15]: https://opensource.com/sites/default/files/uploads/msk-create-15fps.gif (mycroft-msk create working)
|
||||
[16]: https://creativecommons.org/licenses/by-sa/4.0/
|
||||
[17]: https://mycroft-ai.gitbook.io/docs/skill-development/user-interaction/conversational-context
|
||||
[18]: https://realpython.com/python3-object-oriented-programming/
|
||||
[19]: https://twitter.com/linuxovens?lang=en
|
||||
[20]: https://chat.mycroft.ai/community/channels/skills
|
194
translated/tech/20190814 How to install Python on Windows.md
Normal file
194
translated/tech/20190814 How to install Python on Windows.md
Normal file
@ -0,0 +1,194 @@
|
||||
[#]: collector: (lujun9972)
|
||||
[#]: translator: (011011100010110101101111)
|
||||
[#]: reviewer: ( )
|
||||
[#]: publisher: ( )
|
||||
[#]: url: ( )
|
||||
[#]: subject: (How to install Python on Windows)
|
||||
[#]: via: (https://opensource.com/article/19/8/how-install-python-windows)
|
||||
[#]: author: (Seth Kenlon https://opensource.com/users/sethhttps://opensource.com/users/greg-p)
|
||||
|
||||
如何在Windows上安装Python
|
||||
======
|
||||
> 安装Python,启动IDE,然后你就可以在Windows系统下进行编程了。
|
||||
![Hands programming][1]
|
||||
|
||||
你是否想学习编程呢?可以从 [Python][2] 开始,它因为简洁的语法和面向对象的特性而非常受欢迎,是最常见的编程语言之一。而且 Python 是一门解释型语言,这意味着你无需知道如何把 Python 代码编译为机器语言 —— Python 会帮你做到这一点,从而使你能够在编写代码的同时立即进行测试。
|
||||
|
||||
但是你也不能仅仅因为 Python 学习起来简单而低估了它强大的潜能,无论是在 [电影][4]、 [工作室][5]、视频游戏工作室,还是在金融机构、IT机构、制造业,都有 Python 的身影,甚至很多业余爱好者、[艺术家][6]、教师和许多其他人都使用 Python。
|
||||
|
||||
另一方面,Python 也是一门严肃的编程语言,学习它需要付出和实践。还有,你什么都不需要马上做,就几乎可以在任何计算机平台上安装并尝试使用 Python ,因此,如果你使用的是 Windows 操作系统,那本文正适合你。
|
||||
|
||||
如果你使用的是开源的 Linux 操作系统,那你可以 [在 Linux 上安装][7] 并 [尝试使用Python][8]
|
||||
|
||||
### 如何获取 Python
|
||||
|
||||
你可以从 [Python 官方网站][9] 上去下载 Python。在 Python 官方网站下载页,可以将鼠标悬停在 **Downloads** 按钮上,待菜单展开后,再将鼠标悬停在 **Windows** 选项,最后点击按钮就可以下载最新版的 Python 了。
|
||||
|
||||
![Downloading Python on Windows][10]
|
||||
|
||||
或者你也可以直接点击 **Downloads** 按钮,然后在下载页中选择特定的版本去下载。
|
||||
|
||||
### 安装 Python
|
||||
|
||||
下载好安装包后,直接打开就可以启动安装程序了。
|
||||
|
||||
安装时,选择默认的安装路径比较好,最重要的是要将 Python 添加到 Path 中,否则 Python 应用程序不知道它该从哪里找到 Python 必须的运行时环境;默认认安装时并没有选中这一项,需要手动选中安装窗口的 **Add Python 3.7 to Path** ,然后点击继续。
|
||||
|
||||
![Select "Add Python 3 to PATH"][11]
|
||||
|
||||
由于 Windows 需要经过你的批准才会允许安装非 Microsoft 官方发行的应用程序,因此你必须要在弹出 **User Account Control** 系统提示窗口的时候 点击 **Yes** 来继续完成安装。
|
||||
|
||||
![Windows UAC][12]
|
||||
|
||||
这时候你就需要耐心等待,系统会自动将 Python 软件包分发到合适的位置,等待过后,也就意味着你已经成功的安装了 Python ,你就可以愉快的与 Python 玩耍了!
|
||||
|
||||
### 安装一个 IDE
|
||||
|
||||
虽然说你仅需要一个文本编辑器,就可以开始编写 Python 代码了,但是我依然建议你使用 IDE (集成开发环境)来进行开发,这样开发起来就会变得方便很多。IDE 会将文本编辑器和一些好用的 Python 功能集成到一起,使用起来非常友好。你可以考虑选择 IDLE 3 或者 NINJA-IDE 来作为你的 IDE。
|
||||
|
||||
#### IDLE 3
|
||||
|
||||
Python 自带一款 IDE,名字叫 IDLE。虽然你可以使用任何文本编辑器编写 Python 代码,但 IDE 通常会提供 [Notepad++][13] 之类的纯文本编辑器所没有的代码高亮、语法检测等功能,甚至在 IDE 里可以直接通过鼠标点击 **Run** 按钮就能快速运行 Python 代码。
|
||||
|
||||
想要启动 IDLE ,可以点击 Windows 的 **开始** (或者 **Windows**)按钮,然后输入 **Python** 来进行搜索。这时候可能会搜索到多个选项,选择 IDLE 启动就好了。
|
||||
|
||||
![IDLE 3 IDE][14]
|
||||
|
||||
如果在 **开始** 菜单中没有搜到,你也可以在 **开始** 菜单输入 **cmd** (或同时按下键盘 win + R 键) 来启动 Windows 命令提示符,然后输入下面命令来启动 IDLE :
|
||||
|
||||
```
|
||||
`C:\Windows\py.exe`
|
||||
```
|
||||
|
||||
如果还是无法启动的话,可是试着重新安装 Python ,安装时记得务必要在安装向导中选中 **Add Python to PATH** 。详细说明,可以参考 [Python 官方文档][15] 。
|
||||
|
||||
#### Ninja-IDE
|
||||
|
||||
如果你已经有一些编程经验而且你觉得 IDLE 对你来说有些简陋的话,你也可以试试 [Ninja-IDE][16]。 Ninja-IDE 是一款非常出色的 Python IDE, 它具有代码高亮功能,并且他会自动帮你检测诸如拼写错误、引号或括号缺失以及其他语法错误。而且它还可以显示行号(调试的时候会非常有用)、锁进标记甚至可以直接通过点击 **Run** 按钮来运行你的代码。
|
||||
|
||||
![Ninja-IDE][17]
|
||||
|
||||
如果要安装 Ninja-IDE ,你可以访问 Ninja-IDE 的官网 [下载 Windows 安装程序][18] 。步骤跟安装 Python 大同小异:下载安装包、允许 Windows 安装非 Microsoft 官方的应用程序,然后等待完成安装即可。
|
||||
|
||||
Ninja-IDE 安装完成后,双击 Windows 桌面或开始菜单下的 Ninja-IDE 就可以启动了。
|
||||
|
||||
### 告诉 Python 怎么做
|
||||
|
||||
关键字能让 Python 知道你想要做什么。在 IDLE 或者 Ninja-IDE ,打开 **文件** 菜单,创建一个新文件。
|
||||
|
||||
在 Ninja-IDE 中,不要创建一个新项目,而是单独创建一个新文件就可以了。
|
||||
|
||||
在你用 IDLE 或者 Ninja-IDE 新建的文件中,输入以下代码:
|
||||
|
||||
```
|
||||
`print("Hello world.")`
|
||||
```
|
||||
|
||||
* 如果你使用的是 IDLE ,请点击"运行"菜单,选择"运行模块"选项来运行你的程序。
|
||||
* 如果你使用的是 Ninja ,请单击左侧按钮栏中的"运行文件"按钮。
|
||||
|
||||
![Running code in Ninja-IDE][19]
|
||||
|
||||
任何时间当你想要执行代码,IDE 都会提示你先保存当前正在处理的文件,然后再继续。
|
||||
|
||||
**print** 关键字会告诉 Python 打印出你在括号和引号中输入的所有文本。
|
||||
|
||||
但是别高兴地太早,Python 的核心库也就只能访问 **print** 和 **help** 之类的基本关键字、函数等。
|
||||
|
||||
如果想要使用更多的关键字和函数,你就需要使用 **import** 关键字去加载它们。好了,先在你的 IDLE 或者 Ninja 中新建一个文件,命名为 **pen.py** 。
|
||||
|
||||
**警告**:不要把你新建的文件命名为 **turtle.py** ,因为 **turtle.py** 是包含了你要控制的 turtle 程序的文件名称,使用 **turtle.py** 作为文件名会让 Python 感到困惑,因为它以为你想要引入你自己的文件。
|
||||
|
||||
在你新建的文件中输入一下代码,并运行:
|
||||
|
||||
```
|
||||
`import turtle`
|
||||
```
|
||||
|
||||
[Turtle][20] 是一个用起来非常有意思的模块. 把这段代码添加到你的问价内:
|
||||
|
||||
|
||||
```
|
||||
turtle.begin_fill()
|
||||
turtle.forward(100)
|
||||
turtle.left(90)
|
||||
turtle.forward(100)
|
||||
turtle.left(90)
|
||||
turtle.forward(100)
|
||||
turtle.left(90)
|
||||
turtle.forward(100)
|
||||
turtle.end_fill()
|
||||
```
|
||||
|
||||
来看看你可以使用 turtle 模块来绘制出哪些图案。
|
||||
|
||||
想要清空 turtle 绘制的区域的话,你可以使用 **turtle.clear()** 函数。那你知道 **turtle.color("blue")** 是用来做什么的吗?
|
||||
|
||||
我们来试一下更复杂点的程序:
|
||||
|
||||
```
|
||||
import turtle as t
|
||||
import time
|
||||
|
||||
t.color("blue")
|
||||
t.begin_fill()
|
||||
|
||||
counter = 0
|
||||
|
||||
while counter < 4:
|
||||
t.forward(100)
|
||||
t.left(90)
|
||||
counter = counter+1
|
||||
|
||||
t.end_fill()
|
||||
time.sleep(2)
|
||||
```
|
||||
|
||||
给你个挑战,试试修改代码,让它得到下图所示的结果:
|
||||
|
||||
![Example Python turtle output][21]
|
||||
|
||||
当你完成这段代码后,你就可以继续学习更多有意思的模块了。这个 [入门级骰子游戏][] 就是个不错的开始。
|
||||
|
||||
### 保持 Pythonic
|
||||
|
||||
Python 是一门非常有趣的语言,它的模块几乎能实现所有你想要实现的功能。正如你所看到的,Python 入门很容易,只要你对自己有耐心,很快就会发现自己在理解和编写 Python 时能像写汉字一样流畅。你可以在 [Python articles][23] 多阅读关于 Python 的文章,试着为自己编写一些小片段,然后看看 Python 会执行出什么结果。如果想要把 Python 真正融合到你实际工作中,你可以试试 Linux ,Linux 具有在本地可编写脚本的功能,而其他系统却没有。
|
||||
|
||||
祝你好运,记得保持 Pythonic
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://opensource.com/article/19/8/how-install-python-windows
|
||||
|
||||
作者:[Seth Kenlon][a]
|
||||
选题:[lujun9972][b]
|
||||
译者:[LiuWenlong](https://github.com/011011100010110101101111)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://opensource.com/users/sethhttps://opensource.com/users/greg-p
|
||||
[b]: https://github.com/lujun9972
|
||||
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/programming-code-keyboard-laptop.png?itok=pGfEfu2S (Hands programming)
|
||||
[2]: https://www.python.org/
|
||||
[3]: https://opensource.com/article/19/7/get-modular-python-classes
|
||||
[4]: https://github.com/edniemeyer/weta_python_db
|
||||
[5]: https://www.python.org/about/success/ilm/
|
||||
[6]: https://opensource.com/article/19/7/rgb-cube-python-scribus
|
||||
[7]: https://opensource.com/article/19/7/ways-get-started-linux
|
||||
[8]: https://opensource.com/article/17/10/python-101
|
||||
[9]: https://www.python.org/downloads/
|
||||
[10]: https://opensource.com/sites/default/files/uploads/win-python-install.jpg (Downloading Python on Windows)
|
||||
[11]: https://opensource.com/sites/default/files/uploads/win-python-path.jpg (Select "Add Python 3 to PATH")
|
||||
[12]: https://opensource.com/sites/default/files/uploads/win-python-publisher.jpg (Windows UAC)
|
||||
[13]: https://notepad-plus-plus.org/
|
||||
[14]: https://opensource.com/sites/default/files/uploads/idle3.png (IDLE 3 IDE)
|
||||
[15]: http://docs.python.org/3/using/windows.html
|
||||
[16]: http://ninja-ide.org/
|
||||
[17]: https://opensource.com/sites/default/files/uploads/win-python-ninja.jpg (Ninja-IDE)
|
||||
[18]: http://ninja-ide.org/downloads/
|
||||
[19]: https://opensource.com/sites/default/files/uploads/ninja_run.png (Running code in Ninja-IDE)
|
||||
[20]: https://opensource.com/life/15/8/python-turtle-graphics
|
||||
[21]: https://opensource.com/sites/default/files/uploads/win-python-idle-turtle.jpg (Example Python turtle output)
|
||||
[22]: https://opensource.com/article/17/10/python-101#python-101-dice-game
|
||||
[23]: https://opensource.com/sitewide-search?search_api_views_fulltext=Python
|
Loading…
Reference in New Issue
Block a user