What cool things can you do with 10 lines of python code?

Python has won the love of many developers with its concise code. Therefore, more developers are encouraged to use Python to develop new modules, thus forming a virtuous circle. Python can achieve many interesting operations with shorter code. Let's see what interesting things we can achieve with no more than 10 lines of code.

1. Generate QR code

Two-dimensional code is also called two-dimensional barcode. The common two-dimensional code is QR Code. The full name of QR is Quick Response. It is a super popular coding method on mobile devices in recent years, and generating a two-dimensional code is also very simple. In Python, we can generate a QR code through the MyQR module. To generate a QR code, we only need 2 lines of code. We first install the MyQR module. Here we use the domestic source to download:

Dry goods mainly include:

① 200+ Python eBooks (and classic books) should have

② Python standard library information (the most complete Chinese version)

③ Project source code (forty or fifty interesting and reliable training projects and source code)

④ Videos on basic introduction to Python, crawler, network development, and big data analysis (suitable for novice learning)

⑤ Python learning roadmap (say goodbye to inexperienced learning)

pip install qrcode 

After the installation is complete, we can start writing code:

import qrcode

text = input(输入文字或URL:)  
# 设置URL必须添加http://
img =qrcode.make(text)
img.save()                            
#保存图片至本地目录,可以设定路径
img.show()

After we execute the code, a QR code will be generated under the project. Of course, we can also enrich the QR code:

Let's install the MyQR module first

pip install  myqr
def gakki_code():
    version, level, qr_name = myqr.run(
        words=https://520mg.com/it/#/main/2,  
        # 可以是字符串,也可以是网址(前面要加http(s)://)
        version=1,  # 设置容错率为最高
        level='H',  
        # 控制纠错水平,范围是L、M、Q、H,从左到右依次升高
        picture=gakki.gif,  
        # 将二维码和图片合成
        colorized=True,  # 彩色二维码
        contrast=1.0, 
         # 用以调节图片的对比度,1.0 表示原始图片,更小的值表示更低对比度,更大反之。默认为1.0
        brightness=1.0,  
        # 用来调节图片的亮度,其余用法和取值同上
        save_name=gakki_code.gif,  
        # 保存文件的名字,格式可以是jpg,png,bmp,gif
        save_dir=os.getcwd()  # 控制位置

    )
 gakki_code()

The effect diagram is as follows:

insert image description here
In addition MyQR also supports dynamic pictures.

2. Generate word cloud

Word cloud, also known as word cloud, is a visually prominent presentation of "keywords" that appear frequently in text data, and the rendering of keywords forms a cloud-like color picture, so that you can appreciate the main features of text data at a glance. express meaning.

But as an old code farmer, I still like to generate my own word cloud with code. Is it complicated? Does it take a long time? Many texts have introduced various methods, but in fact only 10 lines of python code are required.

Install the necessary libraries first

pip install wordcloud
pip install jieba
pip install matplotlib
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import jieba

text_from_file_with_apath = open('/Users/hecom/23tips.txt').read()

wordlist_after_jieba = jieba.cut(text_from_file_with_apath, cut_all = True)
wl_space_split =  .join(wordlist_after_jieba)

my_wordcloud = WordCloud().generate(wl_space_split)

plt.imshow(my_wordcloud)
plt.axis(off)
plt.show()

That's all, a word cloud is generated like this:

insert image description here

Read these 10 lines of code:

Lines 1 to 3 import the drawing library matplotlib, the word cloud generation library wordcloud and the word segmentation library of jieba;

Line 4 is to read the local file. The text used in the code is "Two or three things about R&D management in the eyes of Lao Cao" in this official account.

Lines 5 to 6, use jieba for word segmentation, and separate the results of word segmentation with spaces;

7 lines, generate word cloud for the text after word segmentation;

Lines 8 to 10, use pyplot to display the word cloud map.

This is one of the reasons I like python, it's concise and clear.

3. Batch cutout

The realization of matting requires the help of the deep learning tool paddlepaddle of Baidu Paddle. We need to install two modules to quickly realize batch matting. The first one is PaddlePaddle:

python -m pip install paddlepaddle -i https://mirror.baidu.com/pypi/simple

There is also a paddlehub model library:

pip install -i https://mirror.baidu.com/pypi/simple paddlehub

For more detailed installation matters, please refer to the official website of Paddlepaddle:
https://www.paddlepaddle.org.cn/

Next, we only need 5 lines of code to achieve batch matting:

import os, paddlehub as hub
humanseg = hub.Module(name='deeplabv3p_xception65_humanseg')        # 加载模型
path = 'D:/CodeField/Workplace/PythonWorkplace/GrapImage/'    # 文件目录
files = [path + i for i in os.listdir(path)]    # 获取文件列表
results = humanseg.segmentation(data={
    
    'image':files})    # 抠图

The cutout effect is as follows:

insert image description here
The left side is the original image, and the right side is the yellow background image filled with the cutout.

4. Text emotion recognition

In front of paddlepaddle, natural language processing also becomes very simple. To realize text emotion recognition, we also need to install PaddlePaddle and Paddlehub. For the specific installation, please refer to the content in Section 3. Then there is our code part:

import paddlehub as hub        
senta = hub.Module(name='senta_lstm')        # 加载模型
sentence = [    # 准备要识别的语句
    '你真美', '你真丑', '我好难过', '我不开心', '这个游戏好好玩', '什么垃圾游戏',
]
results = senta.sentiment_classify(data={
    
    text:sentence})    # 情绪识别
# 输出识别结果
for result in results:
    print(result)

The result of the recognition is a list of dictionaries:

{
    
    'text': '你真美', 'sentiment_label': 1, 'sentiment_key': 'positive', 'positive_probs': 0.9602, 'negative_probs': 0.0398}
{
    
    'text': '你真丑', 'sentiment_label': 0, 'sentiment_key': 'negative', 'positive_probs': 0.0033, 'negative_probs': 0.9967}
{
    
    'text': '我好难过', 'sentiment_label': 1, 'sentiment_key': 'positive', 'positive_probs': 0.5324, 'negative_probs': 0.4676}
{
    
    'text': '我不开心', 'sentiment_label': 0, 'sentiment_key': 'negative', 'positive_probs': 0.1936, 'negative_probs': 0.8064}
{
    
    'text': '这个游戏好好玩', 'sentiment_label': 1, 'sentiment_key': 'positive', 'positive_probs': 0.9933, 'negative_probs': 0.0067}
{
    
    'text': '什么垃圾游戏', 'sentiment_label': 0, 'sentiment_key': 'negative', 'positive_probs': 0.0108, 'negative_probs': 0.9892}

The sentiment_key field contains sentiment information. For detailed analysis, see Python Natural Language Processing Only 5 lines of code are required.

5. Identify whether you are wearing a mask

Here is also a product using PaddlePaddle. We installed PaddlePaddle and Paddlehub according to the above steps, and then started to write code:

import paddlehub as hub
# 加载模型
module = hub.Module(name='pyramidbox_lite_mobile_mask')
# 图片列表
image_list = ['face.jpg']
# 获取图片字典
input_dict = {
    
    'image':image_list}
# 检测是否带了口罩
module.face_detection(data=input_dict)

After executing the above program, the detection_result folder will be generated under the project, and the recognition results will be in it. The recognition effect is as follows:

insert image description here

6. Simple Information Bombing

There are many ways to control input devices in Python, we can use win32 or pynput module. We can achieve the effect of information bombing through a simple loop operation. Here we take pynput as an example, we need to install the module first:

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple/ pynput

Before writing the code, we need to manually get the coordinates of the input box:

from pynput import mouse
# 创建一个鼠标
m_mouse = mouse.Controller()
# 输出鼠标位置
print(m_mouse.position)

There might be a more efficient way, but I wouldn't.

After getting it, we can record the coordinates, and the message window should not move. Then we execute the following code and switch the window to the message page:

import time
from pynput import mouse, keyboard
time.sleep(5)
m_mouse = mouse.Controller()    # 创建一个鼠标
m_keyboard = keyboard.Controller()  # 创建一个键盘
m_mouse.position = (850, 670)       # 将鼠标移动到指定位置
m_mouse.click(mouse.Button.left) # 点击鼠标左键
while(True):
    m_keyboard.type('你好')        # 打字
    m_keyboard.press(keyboard.Key.enter)    # 按下enter
    m_keyboard.release(keyboard.Key.enter)    # 松开enter
    time.sleep(0.5)    # 等待 0.5

I'll admit, this is over 10 lines of code, and it's not high end. Before using QQ to send a message to the trumpet, the effect is as follows:

insert image description here

7. Recognize text in pictures

We can use Tesseract to identify the text in the picture. It is very simple to implement in Python, but it is a bit cumbersome to download files and configure environment variables in the early stage, so this article only shows the code:

import pytesseract
from PIL import Image
img = Image.open('text.jpg')
text = pytesseract.image_to_string(img)
print(text)

Where text is the recognized text. If you are not satisfied with the accuracy, you can also use Baidu's general text interface.

Eight simple games

Getting started with some small examples feels very efficient.

import random
print(1-100数字猜谜游戏!)
num = random.randint(1,100)
guess =guess

i = 0
while guess != num:
    i += 1
    guess = int(input(请输入你猜的数字:))

    if guess == num:
        print(恭喜,你猜对了!)
    elif guess < num:
        print(你猜的数小了...)
    else:
        print(你猜的数大了...)

print(你总共猜了%d %i + 次)

Guess the number of small cases in front of practice

About Python technical reserve

Learning Python well is good, whether it is employment or a side business to make money, but to learn Python, you still have to have a learning plan. Finally, we will share a complete set of Python learning materials to help those friends who want to learn Python!

1. Learning routes in all directions of Python

All directions of Python are to organize the technical points commonly used in Python to form a summary of knowledge points in various fields. Its usefulness is that you can find corresponding learning resources according to the above knowledge points to ensure that you can learn more comprehensively.

2. Learning software

If a worker wants to do a good job, he must first sharpen his tools. The common development software for learning Python is here, which saves everyone a lot of time.

Three, introductory learning video

When we watch videos to learn, we can't move our eyes and brains without hands. The more scientific way of learning is to use them after understanding. At this time, the hands-on project is very suitable.

4. Practical cases

Optical theory is useless. You have to learn to follow along, and you have to do practical exercises before you can apply what you have learned to practice. At this time, you can learn from actual combat cases.

5. Interview information

We must learn Python in order to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Ali, Tencent, and Byte, and some Ali bosses have given authoritative answers. After finishing this set The interview materials believe that everyone can find a satisfactory job.


This full version of Python's full set of learning materials has been uploaded to CSDN. If you need it, you can scan the CSDN official certification QR code below on WeChat to get it for free [ 保证100%免费]

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326838911&siteId=291194637