1-30 essences of python notes

Posted by Wldrumstcs on Wed, 08 Dec 2021 05:42:56 +0100

Note outline

  1. BIF is Built-in Functions. In order to make it convenient for programmers to write scripts quickly (scripts need to be programmed fast!!!), Python provides a wealth of Built-in Functions, which we only need to call directly. For example, the function of print() is to "print to the screen", and the function of input() is to receive user input.
  2. In Python or IDLE, enter dir(builtins) to see the list of built-in methods provided by python (note that there are two underscores before and after builtins). The lower case is BIF. If you want to check the function of a BIF, such as input(), you can enter help(input) in the shell to get the function description of the bif. Oh, the answer should be 68
  3. • variable names can include letters, numbers and underscores, but variable names cannot start with numbers.

4.
In python, \ is division, \ \ is division and% is remainder







##member = [1,2,3,4]

member[0:2] means to copy from the first element. There are two elements in total, namely member[0] and member[1]

5. Tuple:

Note: instead of modifying the original tuple, it generates a new tuple and labels it with the name of temp. If the original tuple has no label, it will be automatically recycled.


Note: tuples cannot be modified or deleted.

functionnotes
capitalize()Change the first character of the string to uppercase
mobile phone$12
catheter$1


Content from: https://blog.csdn.net/qq_45077896/article/details/90521891




d is a decimal integer
-Align left


Use 0 to fill the empty space. The total number of 10 digits is an integer
-Represents left alignment


Returns the object of the iterator
Put this 0x... Cast to list

The index value + value of each list becomes a tuple

016 sequence! Sequence!


Note: tuples cannot be modified or deleted, so the sorted and reversed commands cannot be used directly on tuples

tuple2 = (3.1 ,2.8 ,3.6)
#Isn't this tuple??

def MyFirstFunction(name):
print(name + 'I love you')
MyFirstFunction('niubi')
’The name in the function definition process is called 'formal parameter'
print('passed in '+ name +' is called an argument because Ta is a specific parameter value! ')



Local variable – global variable!


Be sure to align in python
In c language, the else is the if corresponding to the proximity principle

ALT N starts from the first statement executed after IDLE is opened
ALT P starts from the first statement executed after IDLE is opened



#The filter function filter can filter out non-zero elements


Note: lambda x:x%2 is used to judge whether it is odd. If x is odd, 1 is output, otherwise 0 is output; range(10) can generate 10 integers of 0-9, and filter is used to filter non-zero elements; If it is an even number, it is filtered out; If it is an odd number, it is retained, but the output is the original number generated by Lang (10), because lambda is only used to judge whether it is odd or even


0-9 generated by range is given to x, and X is assigned to X after double operation

map() maps the specified sequence according to the provided function.

The first parameter function calls the function function with each element in the parameter sequence and returns a new list containing the return value of each function function.

025 Dictionary: when the index is not easy to use


Dictionary mapping with {} tuple mapping with () list mapping with [] mapping




iterables parameter

026 Dictionary: when the index is not easy to use 2

The fromkey() method is used to create and return a new dictionary. It has two parameters. The first parameter is the key of the dictionary; The second parameter is optional and is the value of the incoming key. If not provided, the default is None
>>> dict1 = {}
>>> dict1.fromkeys((1,2,3))
{1: None, 2: None, 3: None}
>>> dict2 = {}
>>> dict2.fromkeys((1,2,3),"Number")
{1: 'Number', 2: 'Number', 3: 'Number'}
>>> dict3 = {}
>>> dict3.fromkeys((1,2,3),('one','two','three'))
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}

The methods to access the dictionary are key(), values() and items()
key() is used to return the keys in the dictionary, value() is used to return all the values in the dictionary, and item() is, of course, to return all the key value pairs (that is, items) in the dictionary

>>> dict1 = dict1.fromkeys(range(5),'fabulous')
>>> dict1.keys()
dict_keys([0, 1, 2, 3, 4])
>>> dict1.values()
dict_values(['fabulous', 'fabulous', 'fabulous', 'fabulous', 'fabulous'])
>>> dict1.items()
dict_items([(0, 'fabulous'), (1, 'fabulous'), (2, 'fabulous'), (3, 'fabulous'), (4, 'fabulous')])


>>> dict1 =dict.fromkeys(range(5),'fabulous')
>>> for eachkey in dict1.keys():
	print(eachkey)
0
1
2
3
4
>>> for eachValue in dict1.values():
	print(eachValue)
fabulous
 fabulous
 fabulous
 fabulous
 fabulous
		
>>> for eachItem in dict1.items():
	print(eachItem)
(0, 'fabulous')
(1, 'fabulous')
(2, 'fabulous')
(3, 'fabulous')
(4, 'fabulous')
>>> print(dict1[5])
Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    print(dict1[5])
KeyError: 5
>>> print(dict1[4])
fabulous
get()Method provides a more relaxed way to access dictionary items,
When the key doesn't exist, get()The method does not report an error,
Just silently return to the first one None,Means nothing is found:
>>>dict1.get(5)
>>> print(dict1.get(5))
None

If you want to return the specified value when data cannot be found, you can set the corresponding default return value in the second parameter:
>>> dict1.get(5,'Mu you')
'Mu you'
>>> dict1.get(4,'Mu you')
'fabulous'
>>> 4 in dict1
True
>>> 5 in dict1

clear() clears a dictionary

>>> dict1
{0: 'fabulous', 1: 'fabulous', 2: 'fabulous', 3: 'fabulous', 4: 'fabulous'}
>>> dict1.clear()
>>> dict1
{}
Note the index of the stack
>>> a={'full name':'2'}
>>> b=a
>>> b
{'full name': '2'}
>>> a = {}
>>> a
{}
>>> b
{'full name': '2'}

>>>a = b
>>>a
{'full name':'2'}
>>>b
{'full name':'2'}
>>>a.clear
>>>a
{}
>>>b
{}
>>> 
copy()The method is to copy the dictionary (full copy)
····Assignment is not a full copy

>>> a = {1:'one',2:'two',3:'three'}
>>> b = a.copy()
>>> c = a
>>> c
{1: 'one', 2: 'two', 3: 'three'}
>>> a
{1: 'one', 2: 'two', 3: 'three'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}
>>> id(a)
2454888071104
>>> id(b)
2454887935360
>>> id(c)
2454888071104
 assignment---The address is the same   
Assignment: a different label is attached to the same data

>>> c[4]='four'
>>> c
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}


pop()Is the corresponding value of the given key pop-up, popitem()Is a random pop-up item
>>> a.pop(2)
'two'
>>> a
{1: 'four', 3: 'three'}
>>> a.popitem()
(1, 'four')
>>> a
{3: 'three'}

setdefault()Method and get()The method is similar, but setdefault()When the corresponding key value cannot be found in the dictionary, it will be added automatically
>>> a = {1:'one',2:'two',3:'three'}
>>> a.setdefault(2)
'two'
>>> a.setdefault(4)
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: None}
update()Method to update the dictionary

>>> a = {1:'one','Xiaobai':None}

>>> b = {'Xiaobai':'dog'}
>>> a.update(b)
>>> a
{1: 'one', 'Xiaobai': 'dog'}

027 set: in my world, you are the only one

Cousin of the dictionary - set (in Python 3, if you enclose a bunch of numbers in curly braces but do not reflect the mapping relationship, you will think that this pile of things is a set)
>>> num1 = {}
>>> type(num1)
<class 'dict'>
>>> num2 = {1,3,4}
>>> type(num2)
<class 'set'>      set It's a collection 


Set uniqueness--Disorder
>>> num = {1,2,3,4,5,5,4,3,2,1}
>>> num
{1, 2, 3, 4, 5}

num2[2]  An error will be reported. The collection does not support indexing
There are two ways to create a collection:
1,Directly enclose a pile of elements in curly braces;
>>> set1 = {'Small turtle','Squid','Small turtle'}

2,use set()Factory function
>>> set2 = set(['Small turtle','Squid','Small turtle'])
>>> set1 == set2
True
Make fun of it in class

Requirement: remove duplicate elements from the list

[0, 1, 2, 3, 4, 5, 5, 3, 1]

Method I

>>> list1 = [1,2,3,4,5,5,3,1,0]

>>> temp = list1[:]
>>> list1.clear()
>>> list1
[]
>>> for each in temp:
    if each not in list1:
        list1.append(each) #append() means to add an element to the list
        
Method 2
>>> list1 = list(set(list1))
>>> list1
[0, 1, 2, 3, 4, 5]
#set(list1) first converts the list1 list into a set, and list(set(list1)) then converts the set into a list
How to access values in a collection

Because the elements in the collection are disordered, they cannot be accessed with subscripts like sequences, but iterations can be used to read the data in the collection one by one

•have access to for Read out the data in the set one by one

>>> set1 = {1,2,3,4,5,4,3,2,1,0}
>>> for each in set1:
    print(each,end = ' ')

    
0 1 2 3 4 5 


•You can also in and not in Determine whether an element already exists in the collection

>>> 0 in set1
True
>>> 8 in set1
False

use add()Method to add elements to a collection, using remove()Method to delete a known element in the collection:

>>> set1.add(6)
>>> set1
{0, 1, 2, 3, 4, 5, 6}
>>> set1.remove(5)
>>> set1
{0, 1, 2, 3, 4, 6}

Immutable set (freeze the elements) (like pixel group, you can't add or delete the elements in the set at will)

028 document: because I know you, so forever

>>> f = open("C:\\Users\Administrator\Desktop\lecture.txt",encoding ='utf-8')
>>> f
<_io.TextIOWrapper name='C:\\Users\\Administrator\\Desktop\\lecture.txt' mode='r' encoding='utf-8'>
>>> f.read
<built-in method read of _io.TextIOWrapper object at 0x0000023B92B56EE0>
>>> f.read()
'GFW,Ladder, wall climbing'
>>> f.read()
''
The description has pointed to the end of the file, so it is end of file

>>>f=open("C:\\Users\Administrator\Desktop\lecture.txt",encoding ='utf-8')
>>> f.read(5)
'GFW,ladder'
>>> f.tell()
9
 An English character is 2 bytes+A stop sign
>>> f.seek(45,0)
45
>>> f.readline()
'ance\n'
>>> list(f)
	




>>> f.seek(0,0)
0
>>> lines = list(f)
>>> for eachLine in lines:
	print(eachLine)
	
be equal to

>>> f.seek(0,0)
0
>>> for eachLine in f :
	print(eachLine)

>>> f.write("I Love fishc.com")
Traceback (most recent call last):
  File "<pyshell#124>", line 1, in <module>
    f.write("I Love fishc.com")
io.UnsupportedOperation: not writable
#  io error
>>> f = open('E:/test.txt','w')
>>> f.write("I Love fishc.com")
16
>>> f.close()
#If it is closed, it will be saved. If it is not closed, it will be placed in the buffer

029 file: one task

• task: divide the data in the file (record.txt) and save it according to the following rules:

– the conversation of the little turtle is saved separately as boy_ * Txt file (remove "Little Turtle:")

– small customer service conversations are saved separately as girl_ * Txt file (remove "small customer service:")

– there are three conversations in the file, which are saved as boy_1.txt, girl_1.txt,boy_2.txt, girl_2.txt, boy_3.txt, gril_3.txt there are 6 files in total (prompt: different conversations in the file have been split with "========================================================

test1:

f = open("record.txt")

boy = []
girl = []
count = 1

for each_line in f:
    if each_line[:6] != '======':#Determine whether six consecutive are read=
        (role,line_spoken) = each_line.split(':',1)#split: to cut characters,
        #Store the cut two parts in role and line in turn_ In spoken
        if role == 'Small turtle':
            boy.append(line_spoken)#Add what little turtle said to the list boy
        if role == 'Small customer service':
            girl.append(line_spoken)#Add what the customer service said to the list girl
    else:
        file_name_boy = 'boy_' + str(count) + '.txt'
        file_name_girl = 'girl_' + str(count) + '.txt'

        boy_file = open(file_name_boy,'w')#Create a new file in w mode_ name_ Boy named txt file
        girl_file = open(file_name_girl,'w')#And stick boy_ Label for file

        boy_file.writelines(boy)#Write the contents of the list boy to the boy_file
        girl_file.writelines(girl)

        boy_file.close()#Close boy_file file
        girl_file.close()

        boy = []#Empty list boy
        girl = []
        count += 1
		
file_name_boy = 'boy_' + str(count) + '.txt'
file_name_girl = 'girl_' + str(count) + '.txt'

boy_file = open(file_name_boy,'w')
girl_file = open(file_name_girl,'w')

boy_file.writelines(boy)
girl_file.writelines(girl)

boy_file.close()
girl_file.close()#Remember to close the file

test2:

def save_file(boy,girl,count):
    file_name_boy = 'boy_' + str(count) + '.txt'
    file_name_girl = 'girl_' + str(count) + '.txt'

    boy_file = open(file_name_boy,'w')
    girl_file = open(file_name_girl,'w')

    boy_file.writelines(boy)
    girl_file.writelines(girl)

    boy_file.close()
    girl_file.close()

def split_file(file_name):
    f = open(file_name)

    boy = []
    girl = []
    count = 1

    for each_line in f:
        if each_line[:6] != '======':
            (role,line_spoken) = each_line.split(':',1)#split: to cut characters,
            #Store the cut two parts in role and line in turn_ In spoken
            if role == 'Small turtle':
                boy.append(line_spoken)
            if role == 'Small customer service':
                girl.append(line_spoken)
        else:
            save_file(boy,girl,count)

            boy = []
            girl = []
            count += 1


    save_file(boy,girl,count)
    f.close()

split_file('record.txt')
str.split(str="", num=string.count(str)).

030 file system: introduce something on a tall

A module is a file containing the functions and variables you define. The suffix is. py. A module can be introduced by other programs to use the functions in the module.

OS module (Operating System)

For file system access, python generally provides OS modules. As we know, common operating systems include Windows, MAC, OS, Linux, UNIX, etc. the underlying operating systems work differently due to the access principle of file system, Therefore, you may have to consider which file system modules to use for different systems... This is very unfriendly and troublesome, because it means that when your program running environment changes, you have to modify a lot of code accordingly. But our Python is cross platform, so Python has this OS module.

With the OS module, we don't need to care about what module is used under what operating system. The OS module will help you select the correct module and call it.

>>> import os
>>> os.getcwd()
'C:\\WINDOWS\\system32'
>>> os.chdir("E:\\")
>>> os.getcwd()
'E:\\'
>>> os.listdir()
['$RECYCLE.BIN', '248be78d-c1b4-49ce-8076-48127da1153e', 'cd', 'config.db', 'Config.Msi', 'DumpStack.log.tmp', 'LOL', 'MailMasterData', 'MinGW-w64', 'nginx-1.14.2',   'System Volume Information', 'systeminstalldiskconfig.ini',  'Daily tools', 'Desktop files', 'Tinder', 'Elsie', 'Crack software', 'Thunder']
>>> os.mkdir("E:\\A")
>>> os.mkdir("E:\\A\\B")
>>> os.mkdir("E:\\C\\B")
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    os.mkdir("E:\\C\\B")
FileNotFoundError: [WinError 3] The system cannot find the specified path.: 'E:\\C\\B'

How to use common functions about files / directories in os module
Function name --------------------- usage
How to use common functions about files / directories in os module
How to use common functions about paths in os.path module

use one's hands

  1. Write a program to count the number of files of each file type in the current directory. The program implementation is shown in the figure:
import os
 
all_files = os.listdir(os.curdir) # Use os.curdir to indicate that the current directory is more standard
type_dict = dict()
 
for each_file in all_files:
    if os.path.isdir(each_file):
        type_dict.setdefault('folder', 0)
        type_dict['folder'] += 1
    else:
        ext = os.path.splitext(each_file)[1]
        type_dict.setdefault(ext, 0)
        type_dict[ext] += 1
 
for each_type in type_dict.keys():
    print('The common types under this folder are[%s]File %d individual' % (each_type, type_dict[each_type]))
  1. Write a program. The user inputs the file name and the path to start the search to search whether the file exists. If a folder is encountered, enter the folder to continue the search. The program implementation is shown in the figure:
import os
 
all_files = os.listdir(os.curdir) # Use os.curdir to indicate that the current directory is more standard
file_dict = dict()
 
for each_file in all_files:
    if os.path.isfile(each_file):
        file_size = os.path.getsize(each_file)
        file_dict[each_file] = file_size
 
for each in file_dict.items():
    print('%s[%dBytes]' % (each[0], each[1]))

import os
 
def search_file(start_dir, target) :
    os.chdir(start_dir)
    
    for each_file in os.listdir(os.curdir) :
        if each_file == target :
            print(os.getcwd() + os.sep + each_file) # Using os.sep is a more standard program
        if os.path.isdir(each_file) :
            search_file(each_file, target) # Recursive call
            os.chdir(os.pardir) # Remember to return to the previous directory after recursive call
 
start_dir = input('Please enter the initial directory to find:')
target = input('Please enter the target file to find:')
search_file(start_dir, target)
  1. Write a program. The user inputs the path to start the search, finds all video format files under the path (including the subfolder) (it is required to find the format of MP4, RMVB and AVI), and creates a file (vedioList.txt) to store the path of all found files. The program implementation is as follows:

import os
 
def search_file(start_dir, target) :
    os.chdir(start_dir)
    
    for each_file in os.listdir(os.curdir) :
        ext = os.path.splitext(each_file)[1]
        if ext in target :
            vedio_list.append(os.getcwd() + os.sep + each_file + os.linesep) # Using os.sep is a more standard program
        if os.path.isdir(each_file) :
            search_file(each_file, target) # Recursive call
            os.chdir(os.pardir) # Remember to return to the previous directory after recursive call
 
start_dir = input('Please enter the initial directory to find:')
program_dir = os.getcwd()
 
target = ['.mp4', '.avi', '.rmvb']
vedio_list = []
 
search_file(start_dir, target)
 
f = open(program_dir + os.sep + 'vedioList.txt', 'w')
f.writelines(vedio_list)
f.close()
  1. Write a program. The user enters the keyword to find all text files (. txt suffix) containing the keyword in the current folder (if the current folder contains a folder, enter the folder to continue the search). It is required to display the location of the file and the specific location of the key word in the file (the first line and the second character). The program implementation is as follows:
import os
 
def print_pos(key_dict):
    keys = key_dict.keys()
    keys = sorted(keys) # Since the dictionary is out of order, we sort the number of rows here
    for each_key in keys:
        print('Keyword appears on page %s OK, No %s Two positions.' % (each_key, str(key_dict[each_key])))
 
 
def pos_in_line(line, key):
    pos = []
    begin = line.find(key)
    while begin != -1:
        pos.append(begin + 1) # The user's perspective is counted from 1
        begin = line.find(key, begin+1) # Continue finding from next location
 
    return pos
 
 
def search_in_file(file_name, key):
    f = open(file_name)
    count = 0 # Number of record lines
    key_dict = dict() # Dictionary. The specific number of lines where the user stores the key corresponds to the specific location
    
    for each_line in f:
        count += 1
        if key in each_line:
            pos = pos_in_line(each_line, key) # The key is in the corresponding position of each line
            key_dict[count] = pos
    
    f.close()
    return key_dict
 
 
def search_files(key, detail):    
    all_files = os.walk(os.getcwd())
    txt_files = []
 
    for i in all_files:
        for each_file in i[2]:
            if os.path.splitext(each_file)[1] == '.txt': # Determine whether to use text file according to suffix
                each_file = os.path.join(i[0], each_file)
                txt_files.append(each_file)
 
    for each_txt_file in txt_files:
        key_dict = search_in_file(each_txt_file, key)
        if key_dict:
            print('================================================================')
            print('In file[%s]Keyword found in[%s]' % (each_txt_file, key))
            if detail in ['YES', 'Yes', 'yes']:
                print_pos(key_dict)
 
 
key = input('Please put the script in the folder to be found. Please enter the keyword:')
detail = input('Do you need to print keywords[%s]Specific location in the file( YES/NO): ' % key)
search_files(key, detail)

Topics: Python Back-end