A collection of code often used in personal Python

Contents

This is a code memo that I often write in Python2.

Version: Confirmed with Python 2.7.6

String processing

str_util.py



#White space before and after
value.strip()

#String search
value.find('sub') #From before
value.rfind('sub') #From the back

#If not found-1 returned

value.index('sub') #From before
value.rindex('sub') #From the back

#index,ValueError if rindex is not found:Substring not found occurs.

#Uppercase and lowercase conversion of character strings
value.upper()
value.lower()

File input / output

CSV file output

csv_util.py


import csv

w_f = open(output_file, 'w')
writer = csv.writer(w_f, lineterminator='\n') #It is better to specify the line feed code explicitly.

for record in records:
    output_record = []
    for item in record: #If record is in list format, it can be output as it is
        output_record.append(item)
    writer.writerow(output_record)

w_f.close()

Frequency calculation

freq_util.py



#Sort map by key(ascending order)
for key, value in sorted(map.items()):
    print key, value

#Sort map by key(descending order)
for key, value in sorted(map.items(), reverse=True):
    print key, value

#Sort map by value(ascending order)
for key, value in sorted(map.items(), key=lambda x:x[1]):
    print key, value

#Sort map by value(descending order)
for key, value in sorted(map.items(), key=lambda x:x[1], reverse=True):
    print key, value

#Frequency calculation using a counter
from collections import Counter

data_list = [.....]
counter = Counter(data_list)
for key, cnt in counter.most_common():
    print key, cnt

#Top-Get 3
counter.most_common(3)

#Add by update 1
counter.update("aaa") #Breaked down into characters, Counter({'a': 3})Will be.

#Add by update 2
counter.update(["aaa"]) #Count up as a character string properly Counter({'a': 3, 'aaa': 1})

Set arithmetic

combi_util.py


import itertools

data = ['a', 'b', 'c', 'd', 'e']

#List 3 combinations from data.
list(itertools.combinations(data,3))

#Find the permutations in data.
list(itertools.permutations(data))

Function to specify the range

About range and xrange in Python2. If range (1,5) is set, the list [1, 2, 3, 4] will be returned, so memory will be allocated immediately. If the specified range is wide, the memory consumption is large. xrange returns an xrange object. When specifying a large range, it is better to specify this. In Python3, the range function seems to return a range object, so xrange seems to disappear.

python


>>> print range(1, 5)
[1, 2, 3, 4]
>>> print xrange(1, 5)
xrange(1, 5)

Time processing

Convert datetime string to unix time

python


def get_unix_time(datetime_str, format):

    datetime_obj = datetime.datetime.strptime(datetime_str, format)
    return time.mktime(datetime_obj.timetuple())

get_unix_time('2014-12-22 14:03:10', '%Y-%m-%d %H:%M:%S')

Convert from unix time to datetime string

python


def get_datetime_str(unix_time, format):
    return datetime.datetime.fromtimestamp(unix_time).strftime(format)

Recommended Posts

A collection of code often used in personal Python
A collection of Excel operations often used in Python
Python scikit-learn A collection of predictive model tips often used in the field
Python scikit-learn A collection of predictive model tips often used in the field
Code often used in Python / Django apps [prefectures]
Can be used with AtCoder! A collection of techniques for drawing short code in Python!
A collection of commands frequently used in server management
List of Python code used in big data analysis
Generate a first class collection in Python
[Python] A memo of frequently used phrases (by myself) in Python scripts
Summary of methods often used in pandas
Display a list of alphabets in Python 3
Code reading of faker, a library that generates test data in Python
Code reading of Safe, a library for checking password strength in Python
Draw a graph of a quadratic function in Python
Get the caller of a function in Python
Techniques often used in python short coding (Notepad)
Personal notes to doc Python code in Sphinx
Make a copy of the list in Python
Rewriting elements in a loop of lists (Python)
Make a joyplot-like plot of R in python
Output in the form of a python array
Get a glimpse of machine learning in Python
A well-prepared record of data analysis in Python
A personal memo of Pandas related operations that can be used in practice
List of main probability distributions used in machine learning and statistics and code in python
A memorandum of method often used in machine learning using scikit-learn (for beginners)
Create a data collection bot in Python using Selenium
A memorandum when writing experimental code ~ Logging in python
Ruby, Python code fragment execution of selection in Emacs
Group by consecutive elements of a list in Python
Display a histogram of image brightness values in python
A reminder about the implementation of recommendations in Python
Take a screenshot in Python
Create a function in Python
Create a dictionary in Python
Settings often used in Jupyter
Equivalence of objects in Python
[Python] Frequently used library code
2.x, 3.x character code of python
Make a bookmarklet in Python
Python frequently used code snippets
Generate QR code in Python
Image Processing Collection in Python
Draw a heart in Python
Implementation of quicksort in Python
Character code learned in Python
Find out the apparent width of a string in python
A memorandum of stumbling on my personal HEROKU & Python (Flask)
Make a table of multiplication of each element in a spreadsheet (Python)
A collection of competitive pro techniques to solve with Python
Commands often used in the development environment during Python implementation
Get the number of specific elements in a python list
Comparison of exponential moving average (EMA) code written in Python
Developed a library to get Kindle collection list in Python
I tried to summarize the code often used in Pandas
How to develop in a virtual environment of Python [Memo]
Do something like a Python interpreter in Visual Studio Code
[Note] Import of a file in the parent directory in Python
Decrypt one line of code in Python lambda, map, list
Create code that outputs "A and pretending B" in python