search
HomeBackend DevelopmentPython TutorialWhat cool things can be done with ten lines of Python code?

Let’s take a look at what interesting functions we can achieve with no more than 10 lines of code.

1. Generate QR code

QR 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 mobile device in recent years. A popular coding method, and generating a QR 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 choose the domestic source download:

pip install qrcode 

After the installation is completed, 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, it will be generated under the project A QR code. Of course, we can also enrich the QR code:

We first install the MyQR module

pip installmyqr
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()

In addition, MyQR also supports dynamic pictures.

2. Generate word cloud

Word cloud is also called word cloud. It is a visual prominent presentation of "keywords" that appear more frequently in text data and forms key words. The rendering of words forms a cloud-like color picture, so that the main meaning of the text data can be understood at a glance.

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

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 it, the generated word cloud looks like this:

What cool things can be done with ten lines of Python code?

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 respectively;
  • Line 4 is to read a 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 public account.
  • Line 5~6, use jieba to segment the words, and separate the results of the word segmentation with spaces;
  • Line 7, generate a word cloud for the text after word segmentation;
  • In lines 8 to 10, use pyplot to display the word cloud diagram.

This is one of the reasons why I like python, it is simple and clear.

3. Batch cutout

The implementation of cutout requires the help of Baidu Feipiao's deep learning tool paddlepaddle. We need to install two modules to quickly implement batch cutout. Chapter 1 One is PaddlePaddle:

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

and the other is paddlehub model library:

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

Next we only need 5 lines of code You can achieve batch cutout:

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})# 抠图

4. Text emotion recognition

In front of paddlepaddle, natural language processing It also becomes very simple. To realize text emotion recognition, we also need to install PaddlePaddle and Paddlehub. For specific installation, please refer to Part 3. Then comes 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 recognition result is a dictionary list:

{'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, please see Python natural language processing only requires 5 lines of code.

5. Identify whether you are wearing a mask

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

import paddlehub as hub# Load model module = hub.Module(name='pyramidbox_lite_mobile_mask')# Image list image_list = ['face.jpg']# Get the image dictionary input_dict = {'image':image_list}# Check whether it has Mask module.face_detection(data=input_dict)

After executing the above procedure, the detection_result folder will be generated under the project, and the recognition results will be in it.

6. Simple information bombing

There are many ways to control input devices in Python. We can use the win32 or pynput module. We can achieve the effect of information bombing through simple loop operations. Here, taking 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 obtain the coordinates of the input box:

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

There may be a more efficient way, but I won't.

After obtaining it, we can record the coordinates and do not move the message window. 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 admit, this is more than 10 lines of code, and it is not high-end.

7. Identify text in pictures

We can use Tesseract to identify text in pictures. It is very simple to implement in Python, but it requires downloading files and configuring environment variables in the early stage. It’s a bit cumbersome, 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 universal text interface.

八、简单的小游戏

从一些小例子入门感觉效率很高。

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 + 次)

猜数小案例当着练练手


The above is the detailed content of What cool things can be done with ten lines of Python code?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python in Action: Real-World ExamplesPython in Action: Real-World ExamplesApr 18, 2025 am 12:18 AM

Python's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.

Python's Main Uses: A Comprehensive OverviewPython's Main Uses: A Comprehensive OverviewApr 18, 2025 am 12:18 AM

Python is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.

The Main Purpose of Python: Flexibility and Ease of UseThe Main Purpose of Python: Flexibility and Ease of UseApr 17, 2025 am 12:14 AM

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python: The Power of Versatile ProgrammingPython: The Power of Versatile ProgrammingApr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Learning Python in 2 Hours a Day: A Practical GuideLearning Python in 2 Hours a Day: A Practical GuideApr 17, 2025 am 12:05 AM

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor