Github/python/show me the code 25 (1), githubpython
First on the URL https://github.com/Show-Me-the-Code/show-me-the-code
Learn how to use python and remember some common libraries and functions.
Question 0,000th:Add a red number in the upper right corner of your QQ profile picture (or Weibo profile picture), similar to the number of unread messages. Similar to the figure
1 #-*-coding: UTF-8-*-2 import sys 3 import glob, OS 4 from PIL import Image, ImageDraw, ImageFont 5 type = sys. getfilesystemencoding () 6 7 font = ImageFont. truetype ("msyhbd. ttc ", 30) 8 for infile in glob. glob ("*. jpg "): 9 file, ext = OS. path. splitext (infile) 10 im = Image. open (infile) 11 w, h = im. size12 x = w * 0.813 y = h * 0.114 drawSurface = ImageDraw. draw (im) 15 drawSurface. text (x, y), "4", fill = (255, 0), font = font) 16 im. show ()
This question brings the image processing Library: PIL
Image and ImageDraw, ImageFont are compatible, Draw can paint, font can add some stuff such as font
It may be troublesome to find the font name ...... Open the font folder and select any font.
Right-click a property and choose "view name" from the shortcut menu. If the right-click button does not have a property, the font Contains classes .. For example, I have something in bold .. Just open the property and try again.
Question 0,001st:As an independent developer of the Apple Store App, you need to perform a limited-time promotion for your AppGenerate activation code(Or coupons). How can I generate 200 activation codes (or coupons) using Python )?
The activation code is the odd mess code we usually see, with numbers mixed with letters.
The activation code must be unique and independent, and must be stored in the database. Therefore, it must correspond to the id.
# Coding: utf-8import randomimport stringdef create_code (id, length = 10): id _ = hex (id) id _ = id _ [2:] + 'l' length = length-len (id _) chars = string. ascii_letters + string. digits; code = id _ + ''. join ([random. choice (chars) for I in range (length)]) return codedef get_Id (code): id _ = code. split ('l') [0] id = int (id _, 16) return str (id) if _ name _ = "_ main __": for I in range (0,200): code = create_code (I) id = get_Id (code) print code, id # This article focuses on the char list in string, and join, random. choice (chars) Usage
According to the output, we can see that I and id are the same. I is used as the id to generate code, and the code converted to id remains unchanged. Success ~
The chars list is very interesting ~ It turns out this way.
0,002nd questions: Save the 0001 activation codes (or coupons) generated for question 200MySQLIn a relational database.
Question 0,003rd:Save the 0001 activation codes (or coupons) generated for question 200RedisNon-relational databases.
These two questions involve databases ~~ The blogger does not know the database ~~ I will write these two questions later.
Question 0,004th:The number of words in an English text file.
# -*-coding:utf-8 -*—filename = "image.py"key = "import"file = open(filename)text = file.read()beg = 0num = 0while text.find(key) != -1: num = num + 1 text = text.split(key,1)[1]print numfile.close()
You can change both filename and key by yourself ~~~~
Note the find () function. If find () is found, the index is returned. if it cannot be found,-1 is returned. Therefore, if find () cannot be directly written. In any case, the return value is ...... So be sure to write it! =-1 to make a correct judgment
Question 0,005th:You have a directory with a lot of photos installed. The size of these photos is not larger than the iPhone 5 Resolution.
# -*- coding:utf-8 -*-import glob,osfrom PIL import Imagesize = 200,200for file in glob.glob('*.jpg'): filename,ext = os.path.splitext(file) im = Image.open(file) w,h = im.size im.thumbnail(size) im.save(filename + 'thumbnail.jpg','JPEG')
OS. path. the splitext () function returns two parts: The first part is the file name (which may contain the path), the last part is the type name, glob. glob ("") searches for the files in the current directory. To obtain the current directory, use OS. getcwd (). There are too many similar methods in python.
Question 0,006th:You have a directory that keeps your diary for a month. It is a txt file. To avoid word segmentation problems, if the content is in English, please count the words that you think are the most important in each diary.
The most important word is the most frequently used word.
# coding:utf-8import osimport sysimport refrom collections import Countertype = sys.getfilesystemencoding()def getCounter(file): f = open(file) r = re.findall(r'[A-Za-z]+',f.read()) return Counter(r)if __name__ == "__main__": total_counter = Counter() for infile in os.listdir(os.getcwd()): filename,ext = os.path.splitext(infile) if ext == '.py':# total_counter += getCounter(infile) print filename print getCounter(infile).most_common(2)# print total_counter.most_common()[0][0]
This is a magic counter! Counter class will automatically count the internal data, http://www.pythoner.com/205.html this web site has a detailed explanation
Question 0,007th:There is a directory where the program you have written is used to count how many lines of code you have written. Including empty rows and comments, but must be listed separately.
#coding:utf-8import osimport refrom collections import Counterannotation = r'^\#.'space = r'^\s+$'if __name__ == "__main__": for i in os.listdir(os.getcwd()): code,blank,note = 0,0,0 filename,ext = os.path.splitext(i) if ext == '.py': with open(i) as f: line = f.readline() while line: if re.match(space,line): blank += 1 elif re.match(annotation,line): note += 1 else: code += 1 line = f.readline() print filename print "code:%d, blank:%d, note:%d"%(code,blank,note)
Also run in the current directory ...... The regular expressions of comments and space characters are defined. Because the regular expressions that do not write code are simply represented by else, what is different from c is that else if is written as elif ......
Re. match () is the capture. The first parameter is the regular expression, and the second parameter is the string you checked.
Question 0,008th:An HTML file to findBody.
#coding:utf-8import glob,osimport requestsfrom bs4 import BeautifulSoupimport systy = sys.getfilesystemencoding()url = "https://github.com/Show-Me-the-Code/python/blob/master/Forec/0008/0008.py"html = requests.get(url)soup = BeautifulSoup(html.text,"html.parser")print soup.body.text.encode('GBK','ignore').decode('GBK')
The famous bs4 !!!!
Crawlers .................. Using urllib to crawl down and then partition... index... although it can also make results, it is really a pain point.
Beautifulsoup will structure the html code. Soup. body. text refers to all characters of the body. Of course, you can also try to output soup. body. div ...... However, this output is a div that does not contain sub-structures. Otherwise, it cannot be detected ~~~ So how can we clearly output a tag hidden in a deep and deep structure? This is what we see below.
Question 0,009th:An HTML file to findLink. Replace it with the <a> tag to find... Good.
Question 0,013rd:Use Python to write a program for image crawling. Click the Japanese girl picture in the link :-)
# Coding: utf-8import requestsimport urllib2from bs4 import BeautifulSoupimport lxml.html url = "http://tieba.baidu.com/p/2166231880" html = requests. get (url) soup = BeautifulSoup (html. text, "html. parser ") lis = soup. find_all ('img ') count = 1for img in lis: src = img. attrs ['src'] start = src. rfind ('/') + 1 end = src. rfind ('? ') If src. rfind ('? ')! =-1 else len (src) name = src [start: end] # print name filepath = 'e:/image/'+ str (count) + name with open (filepath, 'wb ') as f: # image_data = urllib2.urlopen (src ). read () # bs4 does not seem to support image_data = requests. get (src ). content # bs4 usage f. write (image_data) count + = 1
Note the find_all function .... No matter how deep this img tag is .. So we can find them.