Unlock 20+ Python Tricks: From Image Processing to Train Ticket Queries

This guide presents a collection of practical Python snippets covering image manipulation with Pillow, video downloading via youtube-dl, object introspection, music bot usage, financial data retrieval with Tushare, vulnerability lab setup, Beijing bus API queries, article extraction, QR code generation, fake user agents, HTTP request statistics, shell commands, Chinese text sentiment analysis, proxy handling, Zhihu API access, password breach checking, Nginx log analysis, and train ticket queries.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Unlock 20+ Python Tricks: From Image Processing to Train Ticket Queries

Image Processing with Pillow

Install Pillow and use it to open an image, modify its pixels, and save a new file.

pip install pillow
from PIL import Image
import numpy as np
a = np.array(Image.open('test.jpg'))
b = [255, 255, 255] - a
im = Image.fromarray(b.astype('uint8'))
im.save('new.jpg')

Download International Videos with youtube-dl

Install youtube-dl and download a video from YouTube.

pip install youtube-dl
pip install -U youtube-dl
youtube-dl "http://www.youtube.com/watch?v=-wNyEUrxzFU"

Inspect Object Attributes and Methods

Use pdir2 to list all attributes of a module such as requests.

pip install pdir2
import pdir, requests
pdir(requests)

Typical attributes include __cached__, __file__, __loader__, __name__, __package__, __path__, __spec__, and many others like ConnectionError, Timeout, HTTPError, etc.

Python Music Bot for NetEase Cloud Music

Install the ncmbot package, log in with phone and password, and retrieve a user's playlist.

pip install ncmbot
import ncmbot
bot = ncmbot.login(phone='xxx', password='yyy')
playlist = bot.user_play_list(uid='36554272')

Financial Data Retrieval with Tushare

Install tushare and fetch daily trading data for all stocks of the most recent trading day.

pip install tushare
import tushare as ts
data = ts.get_today_all()

The returned fields include code, name, change percent, trade price, open, high, low, close, volume, turnover rate, etc.

Open‑Source Vulnerability Lab Setup

Install Docker, Docker‑Compose, clone the vulhub repository, and start a specific vulnerable environment.

curl -s https://bootstrap.pypa.io/get-pip.py | python3 -
apt-get update && apt-get -y install docker.io
pip install docker-compose
git clone https://github.com/phith0n/vulhub.git
cd vulhub
cd nginx_php5_mysql
docker-compose build
docker-compose up -d

After testing, shut down and remove the environment with docker-compose down.

Beijing Bus Real‑Time API

Install the required package and use it to list all bus lines, search a specific line, and obtain real‑time data for a station.

pip install -r requirements.txt
from beijing_bus import BeijingBus
lines = BeijingBus.get_all_lines()
line = lines[0]
print(line.id, line.name)
realtime = line.get_realtime_data(1)

The real‑time data includes bus ID, latitude, longitude, next station name, distance, and estimated arrival times.

Article Extraction with Goose

Clone the Goose repository, install dependencies, and extract cleaned text from a URL.

git clone https://github.com/grangier/python-goose.git
cd python-goose
pip install -r requirements.txt
python setup.py install
from goose import Goose
from goose.text import StopWordsChinese
g = Goose(stopwords_class=StopWordsChinese)
url = 'http://www.bbc.co.uk/zhongwen/simp/chinese_news/2012/12/121210_hongkong_politics.shtml'
article = g.extract(url=url)
print(article.cleaned_text[:150])

Artistic QR Code Generator

Install MyQR and generate a QR code with custom styling.

pip install MyQR
myqr.run('https://example.com', version=10, level='H')

Fake User‑Agent for Browser Spoofing

Install fake-useragent and obtain random user‑agent strings for different browsers.

pip install fake-useragent
from fake_useragent import UserAgent
ua = UserAgent()
print(ua.ie)
print(ua.msie)
print(ua.opera)
print(ua.chrome)

Beautify Curl Output with httpstat

Install httpstat to get detailed timing statistics for HTTP requests.

pip install httpstat
httpstat https://httpbin.org/get

Python Shell Commands with sh

Install sh and run shell commands like ifconfig from Python.

pip install sh
from sh import ifconfig
print(ifconfig('eth0'))

Chinese Text Sentiment Analysis

Use SnowNLP for Chinese sentiment analysis and TextBlob for English.

pip install snownlp
pip install textblob
from snownlp import SnowNLP
from textblob import TextBlob
text = "I am happy today. I feel sad today."
blob = TextBlob(text)
print(blob.sentiment)
s = SnowNLP('这个东西真心很赞')
print(s.sentiments)
print(s.words)
print(s.tags)
print(s.pinyin)

Proxy Fetching and Validation

Install getproxy and use its help and validation options.

pip install getproxy
getproxy --help
getproxy --in-proxy proxies.txt --out-proxy valid.txt

Zhihu API Access

Install the Zhihu API client, create a Zhihu instance, and fetch user information.

pip install git+https://github.com/lzjun567/zhihu-api.git --upgrade
from zhihu import Zhihu
zhihu = Zhihu()
user = zhihu.user(user_slug="xiaoxiaodouzi")
print(user['name'], user['headline'], user['avatar_url'])

Password Breach Query Module

Install leakPasswd and check if a password appears in known breaches.

pip install leakPasswd
import leakPasswd
leakPasswd.findBreach('taobao')

Nginx Access Log Analysis with ngxtop

Install ngxtop and view summary and detailed statistics of an Nginx log.

pip install ngxtop
ngxtop

The summary shows request counts, average bytes sent, and status code distribution; the detailed view lists request paths with counts and byte statistics.

Train Ticket Availability Query

Install iquery and use its commands to query train tickets, movies, lyrics, lotteries, and more.

pip install iquery
iquery -c lottery
iquery -m movie
iquery -p <city>
iquery -l song [singer]
iquery -dgktz <from> <to> <date>

Options include -h for help and flags for specific services such as -dgktz (high‑speed train), -m (movies), -p (hospital checks), and -l (lyrics).

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonTutorialcode snippetsdata-processing
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.