python 高效写法_5条使您的生活更加高效的python技巧

python 高效写法

Python is the most in-demand programming language today and much of it is attributed to its easy learning curve.

Python是当今需求最大的编程语言,其主要原因是易于学习。

But a lot of credit for its popularity also goes to the wide variety of modules it provides. No wonder it’s a great choice for automation and is almost indispensable from utility tasks.

但是,它的受欢迎程度也归功于它提供的各种模块。 难怪它是自动化的绝佳选择,并且几乎是实用程序任务中必不可少的。

You could be a data scientist or a front end developer or just an analyst but the following list of Python tricks would help one and all. Some of these might be obvious while others’ could blow away your mind.

您可能是数据科学家,前端开发人员,也可能只是分析师,但是以下列出的Python技巧将对您有所帮助。 其中一些可能很明显,而另一些则可能会让您大吃一惊。

查看最近的电子邮件并将所有未标记的内容标记为从命令行看到的 (View Recent Emails And Mark All Unread As Seen From Command Line)

How many times were you forced to switch from the terminal to an internet browser just to view the recent emails? It happens a few times for everyone one of us.

您被迫从终端切换到Internet浏览器仅几次以查看最近的电子邮件? 对于我们每个人来说,它都会发生几次。

You could accelerate your workflow and boost your productivity by getting rid of this context switch. Simply use the python imaplib module that lets you log into your email and fetch emails.

通过摆脱上下文切换,您可以加快工作流程并提高生产率。 只需使用python imaplib模块,该模块即可让您登录电子邮件并提取电子邮件。

The library lets you filter emails by date, subject, sender, and more. So, with the following piece of code, you can fetch the latest n emails without manually logging into the browser:

该库使您可以按日期,主题,发件人等过滤电子邮件。 因此,使用以下代码,您无需手动登录浏览器即可获取最新的n封电子邮件:

Image for post
Gist Link 要点链接

RFC822 is an Internet Access Message protocol. You can also look up the Subject , Content and Date from every email response.

RFC822是Internet访问消息协议。 您还可以从每个电子邮件回复中查找SubjectContentDate

Note: For Gmail accounts with two-factor authentication, passing the password in the login method won’t work. You need to generate a token and set it in the password field by referring the below steps:

注意:对于具有两重身份验证的Gmail帐户,无法使用登录方法传递密码。 您需要生成令牌并通过参考以下步骤在密码字段中进行设置:

1. Log into your Gmail account.
2. Navigate to https://security.google.com/settings/security/apppasswords
3. In 'select app' choose 'Custom', give it any name name and press generate.
4. It will give you a token which you can paste in the above script.

Nowadays our inbox is full of promotional emails which only increase the inbox unread count. Selecting all messages and marking them as read is a time-consuming task when your inbox has more than 100 pages.

如今,我们的收件箱中充满了促销电子邮件,只会增加收件箱中的未读邮件数。 当收件箱中有100页以上时,选择所有邮件并将其标记为已读是一项耗时的工作。

Luckily, the above imap module lets you search for UNSEEN messages and set them as read. First, change the search filter of the previous code to this:

幸运的是,上述imap模块可让您搜索UNSEEN消息并将其设置为已读。 首先,将先前代码的搜索过滤器更改为此:

mail.search(None, '(UNSEEN)')

Finally, add the following piece of code in the for-loop:

最后,在for循环中添加以下代码:

original = email.message_from_bytes(response_part[1])
mail.store(num,'+FLAGS','\\Seen')

The backtick Seen is important. I managed to reduce the unread count of my inbox to zero with the above script!

倒引号Seen是很重要的。 通过上述脚本,我设法将收件箱的未读计数减少为零!

2.视频下载器 (2. Video Downloader)

Everyone loves watching YouTube videos. Few of us even wish to save a few video files locally. To our surprise,youtube-dl Python module is just for that.

每个人都喜欢看YouTube视频。 我们中甚至没有几个人希望在本地保存一些视频文件。 令我们惊讶的是, youtube-dl Python模块仅用youtube-dl目的。

Simply install the package and run it on the command line with the YouTube link as shown below:

只需安装该软件包,然后在带有YouTube链接的命令行上运行它,如下所示:

pip install youtube-dl> youtube-dl <Video Link Here>

But sometimes, we’d love to customize the download options. For instance, downloading multiple tracks or a playlist or setting the output directory and choosing the video format by resolution.

但是有时候,我们很乐意自定义下载选项。 例如,下载多个轨道或播放列表,或者设置输出目录并通过分辨率选择视频格式。

Image for post

The great thing about this library is that it lets you download video links outside of YouTube as well.

该库的优点在于,它还可以让您下载YouTube以外的视频链接。

3.从命令行获取库存更新 (3. Get Stock Updates From Command Line)

How often have you looked up currency conversion rates on Google? It’ll certainly be a good number when people travel. And if you’re someone who watches stock markets passively, having a command-line python script can certainly help. Especially, if you’d want to take a quick sneak peek during work.

您多久在Google上查询一次货币兑换率? 人们出行时肯定会是一个好数目。 而且,如果您是被动地关注股市的人,那么使用命令行python脚本肯定会有所帮助。 特别是,如果您想在工作期间快速浏览一下。

We have Python’s yfinance which is just the library you’d need for tracking stocks.

我们有Python的yfinance ,这只是您跟踪股票所需的库。

pip install yfinance

yfinance provides us with lots of data such as stock info, historical data, splits, dividends, quarterly_financials and more. All of them are encompassed in a Ticker module.

yfinance为我们提供了大量的数据,如股票信息,历史数据,拆分,分红等quarterly_financials多。 所有这些都包含在Ticker模块中。

Though there isn’t any straightforward way to fetch the realtime value of a stock, we can use the following workaround:

尽管没有任何直接的方法来获取股票的实时价值,但是我们可以使用以下解决方法:

q = yf.Ticker("AAPL")
data_frame = q.history("1d")
price = data_frame["Close"].values[0print(f'Apple current stock price: {price}')

The above code works like a charm but in case you’re looking to listen to multiple tickers you could do that as well with the following piece of code:

上面的代码就像一个咒语,但是如果您想听多个代码,您也可以使用以下代码来做到这一点:

tickers = yf.Tickers('msft aapl amzn')print(tickers.tickers.MSFT.history("1d")["Close"].values[0])print(tickers.tickers.AAPL.history("1d")["Close"].values[0])print(tickers.tickers.AMZN.history("1d")["Close"].values[0])

Similarly, if you’re looking to get the currency exchange rates, use freecurrencyrates.com. Here’s the Python script for it.

同样,如果您想获取货币汇率,请使用freecurrencyrates.com这是它的Python脚本

4.转换mp4到mp3到文本 (4. Convert mp4 to mp3 to text)

Python’s pydub module lets you to audio processing tasks that range from video conversion to straight out mixing different files.

Python的pydub模块可让您执行从视频转换到直接混合不同文件的音频处理任务。

Staying true to its name, you can also tweak the tones by doing pitch modulation or setting certain segments of the audio louder or quieter. For now, we’ll see how easy it is to extract mp3 files from an mp4 video:

保持其名称的真实性,您还可以通过进行音高调制或将音频的某些片段设置得更大或更安静来调整音调。 现在,我们将看到从mp4视频中提取mp3文件有多么容易:

from pydub import AudioSegmentAudioSegment.from_file("/path_to_video").export("~/output.mp3", format="mp3")

AudioSegment is the container to load, transform, and save audio files.

AudioSegment是加载,转换和保存音频文件的容器。

Next, let’s do a speech to text transcription from the audio file. First, install the SpeechRecognition module using pip. Next, we’ll export the mp3 as a wav file and run the transcription over it:

接下来,让我们对音频文件中的文本转录进行演讲。 首先,使用pip安装SpeechRecognition模块。 接下来,我们将mp3导出为wav文件并对其进行转录:

Image for post

5.从视频中提取图像帧 (5. Extract Image Frames From Video)

Last but not the least, we have a Python script that’s exclusively for data scientists.

最后但并非最不重要的一点是,我们有一个专用于数据科学家的Python脚本。

Data scientists are always looking to collect more data when training their models and videos are one of the biggest sources for accessing images.

数据科学家在训练模型时一直希望收集更多数据,而视频是访问图像的最大来源之一。

Gladly, OpenCV which boasts of a range of image processing techniques can do the extraction of frames from a video for you.

很高兴,拥有多种图像处理技术的OpenCV可以为您提取视频中的帧。

Simply install the opencv-python module with pip as shown below:

只需使用pip安装opencv-python模块,如下所示:

pip install opencv-python

Run the following script on any video file to get jpeg images from each frame.

在任何视频文件上运行以下脚本,以从每个帧获取jpeg图像。

import cv2
videocap = cv2.VideoCapture('input.mp4')
success,image = videocap.read()
count = 0while success:
cv2.imwrite("frame%d.jpg" % count, image)
success,image = videocap.read()
print('Read a new frame: ', success)
count += 1

Now, the above script would create too many duplicate images as we haven’t specified any frame count.

现在,由于我们尚未指定任何帧数,因此上述脚本将创建过多的重复图像。

To restrict the number of frames extracted per second add the following line of code before cv2.imwrite inside the while loop above:

要限制每秒提取的帧数, cv2.imwrite在上述while循环内的cv2.imwrite之前添加以下代码行:

videocap.set(cv2.CAP_PROP_POS_MSEC,(count*1000))

This would capture only one frame per second. You can change it accordingly for your use case.

每秒只能捕获一帧。 您可以针对您的用例进行相应更改。

OpenCV tasks aren’t just limited to data collection. You can run computer vision tasks on the extracted frames. Running blur checks or image similarity requests are just two of the many use cases you can perform.

OpenCV任务不仅限于数据收集。 您可以在提取的帧上运行计算机视觉任务。 运行模糊检查或图像相似性请求只是您可以执行的许多用例中的两个。

带走 (Takeaway)

Python’s module ecosystem makes it possible to run complex tasks in a plug and play fashion. The best thing is you don’t need coding knowledge to run the above tasks.

Python的模块生态系统使得可以即插即用的方式运行复杂的任务。 最好的事情是,您不需要编码知识即可运行上述任务。

On a closing note, if you’re looking to pass data from one Python script to another do the following:

最后,如果您希望将数据从一个Python脚本传递到另一个脚本,请执行以下操作:

#second_script.pyfrom first_cript import variableprint(f'Hello {variable}')

I hope you find the above collection of Python scripts useful and use these cool tricks in your daily tasks.

希望上面的Python脚本集合有用,并在日常任务中使用这些很酷的技巧。

That’s it for this one. Thanks for reading.

这就是它了。 谢谢阅读。

翻译自: https://towardsdatascience.com/5-python-tricks-to-make-your-life-more-productive-974ebeb54a53

python 高效写法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值