Common library python 1

time libraries and library datetime

time library

Processing time is the standard libraries, it can be used for performance analysis

Time to get

time () to get the current timestamp, began floating point 1970.1.1 00.00

the ctime () to get the current time and a readable function of time

gmtime, () generating a computer format that can be processed

Time Format

strftime (tpl, ts) tpl formatted template string, the effect is used to define the output time ts is a computer-type internal variables

Time strptime (str, tpl) is defined as a string internal computer can operate

Format string

  • % Y Year 0000-9999
  • 01 to 12% m Month
  • % B name of the month such as April
  • % B abbreviated month name as Apr
  • 01 to 31% d Date
  • % A week full write
  • % A week abbreviation Sun
  • 00% H ~ 23 hours
  • 01 to 12% h h
  • % P AM PM identifiers AM, PM
  • 00% M ~ 59 minutes
  • 00 seconds to 59% S

Timing the application

sleep (s) make sleeps s seconds

Exact numerical values ​​perf_counter () CPU level, when the difference value is expressed with accuracy, called twice, a difference of elapsed time

Examples of text printing operation progress bar

Single-line dynamic refresh bar:

  • Refresh essence is: before covering with the character after the printed characters
  • You can wrap: print () needs to be controlled. The default print will wrap
  • To be able to roll back: back to the print position the cursor before \ r

Example:

#TextProBarV1.py
import time
for i in range(101):
    print("\r{:3}%".format(i),end="")
    time.sleep(0.1)
    

Here Insert Picture Description

datetime library

from datetime import datetime

from datetime import time delta

1) Get the current date and time

today = datetime.today () # return the current time is always 0

print ( "current time")

print(today)

today1 = datetime.now () # returns the current date and time

now.hour # 时

now.minute # 分

now.isoweekday () # returns of 1-7 representatives Monday - Sunday;

now.weekday () # returns of 0-6 representatives Monday - Sunday to standard formats% w 1-6 said Monday - Saturday, 0 for Sunday

print( today1 )

today2 = datetime.utcnow () # returns the current eight districts in Eastern Time is less than the current time 8 hours

print(today2)

2) Get the specified date and time, addition and subtraction

time= datetime(2019, 5, 12, 12, 13, 14)

d= time + timedelta(weeks=0, days=0, hours=0, minutes=0, seconds=0, milliseconds=0, microseconds=0, )

# Followed by "week", "day", "hour", "minute", "second", "ms", "sec"

print(time)

print(d)

time1 = "2019-5-12 12:13:14" # string date

d1 = datetime.strptime(str(time1),’%Y-%m-%d %H:%M:%S’)

plus = d1 + delta h (days = 1) # 加

minus = d1 - time delta (days = 1) # 减

print(time1)

print(d1)

print (more)

print(minus )

time2= 20190512121314

d2 = datetime.strptime(str(time2),’%Y%m%d%H%M%S’)

delta = d 2 + delta h (days = 1)

print(time2)

print(d2 )

print(delta)

3) Date datetime-timestamp timestamp each turn

now_stamp = time.timestamp()

print ( 'corresponding to the specified time stamp:', now_stamp)

print ( 'local time corresponding to:', datetime.fromtimestamp (now_stamp))

print ( 'UTC Time:', datetime.utcfromtimestamp (now_stamp))

print ( 'Day of the week:', datetime.fromtimestamp (now_stamp) .weekday ())

4) datetime time into a string str

now = datetime.now()

print ( 'current time:', now)

print(now.strftime(’%Y%m%d%H%M%S’))

random library

The basic random number function:

SEED () is selected from seeds not time the computer system is used as the seed, the same seed as a random number sequence

random () generates a random number (generated number between 0 and 1)

Extended random number function:

randint (a, b) generating an integer between [a, b]

getrandbits (k) to generate a random integer k bits

uniform (a, b) generates a random decimal between [a, b]

Random integer randrange (m, n) to generate a [m, n) between the step size in k

Choice (seq) select a random element from a sequence seq

shuffle (seq) the sequence of randomly arranged elements seq

Example:

Monte Carlo simulation pi

PyInstaller library

Py file can be packaged such that an executable file

Using the command line,

pyinstaller -F filename

Then will generate a few folders, the other can be deleted, only one folder (dist) has a useful executable file

Common parameters:

-h View Help

--clean clean up temporary files in the packaging process

-D --onedir defaults, generate dist folder

-F --onefile generated only in a separate package file folder dist

-i <icon file name .ico> Specifies the icon packager used (icon) file

Here Insert Picture Description

OS library

Path operations

os.path sub-library

Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description

etsize (path) Returns the path corresponding to the size of the file, in bytes

Process Management

os.system(command)

Corresponds to the input on the command line

Environmental parameters

Here Insert Picture Description

os.getlogin () to get the current system login user name

os.cpu_count () number of the current system CPU

Here Insert Picture Description

jieba Hyogo

Excellent Chinese third-party libraries: for the Chinese word frequency statistics.

Of the Chinese text word there are three modes

  • Precise and accurate texts be separated, there is no redundancy mode
  • Full mode all possible words in the text are scanned, redundant
  • Search engine mode in precise patterns based on long-term segmentation again

Common Functions

jieba.lcut (s) used to fine mode, it returns a list of the result word type

jieba.lcut (s, cut_all = true) full mode, returns a list of the result word type, redundant

jieba.lcut_for_search (s) search mode, the result returns a word list type, redundant

jieba.add_word (w) w add a new word to the dictionary word

Text word frequency statistics

from jieba import *

txt = open ( 'new era of socialism with Chinese characteristics .txt', 'r', encoding = 'utf-8'). read ()

words = lcut(txt)

counts = {}

for word in words:

      if len\(word\)==1:

          continue

    else:

          counts\[word\] = counts.get\(word, 0\)\+1

items = list(counts.items())

items.sort(key=lambda x: x[1], reverse=True)

for i in range(10):

word, count = items[i]

print("(’{0}’, {1})".format(word, count))

turtle library

# Library introduced: import turtle

                   from turtle import  \* (可能发生函数重名)

 import 库名 as 想要的库名

turtle brush control function

turtle.penup () # turtles flying through the sky, do not dwell brush trajectory

turtle.pendown () # corresponding to the upper, paired

turtle.pensize (width) alias turtle.width (width) # waist turtles, pen width

turtle.pencolor(color)

#color the color string (turtle.pencolor ( "red"))

Or r, g, b values ​​(turtle.pencolor ((0.63,0.12,0.65))) // tuple type

Motion control function

turtle.foreward (d) alias turtle.fd (d) # turtles go straight, go straight ahead, d is the distance may be negative

turtle.circle (r, extent = None) # The arcuate (rad) the angle of the radius r the center default extent drawn at a distance of r on the left Turtle. Do not give a second argument, a default circle.

Direction control function

turtle.setheading (angle) alias turtle.seth (angle) # change Turtles angle, change the direction of travel angle change direction turtles go angles. // absolute angle

turtle.left (angle) # relative angle

turtle.rigth (angle) # relative angle

wordcloud library

Word cloud, visualization

  • wordcloud.WordCloud () represents a word cloud
  • You can configure parameters, loading text, etc.

Instructions

First, create a word cloud object.

w=wordcloud.WorldCloud()

  • Configuration object parameters
  • Load text word cloud
  • Output word cloud file

method:

w.generate (txt) loading into the text object txt WorldClound

w, to_file (filename) of the output word cloud image file, png or jpg format

worldcloud do what thing?

1. Split: words separated by spaces

2. statistics: the number of times the word appears and filters

3. Font: Font Size configuration according to statistics

4. Layout: Environment Color Size

Which parameters can be loaded?

width image width

height Image Height

min__ font __ specified word cloud size in the smallest font size, the default number 4

max __ font __ specify the size of the largest word cloud. . According to the height conditions

Font_step step interval specified word cloud font size, the default is 1

Path font_path specify the font file, the default None

The maximum number of words max_words word cloud shows

Stop_words word cloud word list to specify the list of excluded words that are not displayed

The overall shape of the external configuration word cloud:

Here Insert Picture Description

Example:

Here Insert Picture Description

Released nine original articles · won praise 7 · views 595

Guess you like

Origin blog.csdn.net/qq_43390703/article/details/104188785