


What interesting things can be accomplished 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 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, 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 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()
The rendering is as follows:
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, the generated word cloud is like this:
python -m pip install paddlepaddle -i https://mirror.baidu.com/pypi/simpleand the other is paddlehub model library:
pip install -i https://mirror.baidu.com/pypi/simple paddlehubFor more detailed installation information, please see the official website of PaddlePaddle: https://www.paddlepaddle.org.cn/ Next we only need 5 lines of code to 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})# 抠图The cutout effect is as follows:
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 emotional information. For detailed analysis, please see Python natural language processing only requires 5 lines code. 5. Identify whether you are wearing a maskThis 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 # 加载模型 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:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple/ pynputBefore 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 don't know how. 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. Before using QQ, the effect of sending messages to the trumpet is as follows:
import pytesseract from PIL import Image img = Image.open('text.jpg') text = pytesseract.image_to_string(img) print(text)
其中text就是识别出来的文本。如果对准确率不满意的话,还可以使用百度的通用文字接口。
八、简单的小游戏
从一些小例子入门感觉效率很高。
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 interesting things can be accomplished with ten lines of Python code?. For more information, please follow other related articles on the PHP Chinese website!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment