Hướng dẫn dùng sliceworks python

import argparse

parser = argparse.ArgumentParser[]
parser.add_argument['-c', '--com-port', metavar='N', type=int, required=True, help='HART modem com port']
parser.add_argument['-s', '--slave-address', metavar='N', type=int, default=0, help='HART slave address']
parser.add_argument['-l', '--log', action='store_true', help='log to file']
parser.add_argument['-v', '--verbose', action='store_true', help='print values to console']
args = parser.parse_args[]

logger = setup_logging[args.verbose, args.log]

# picking up piece of string between separators
# function using partition, like partition, but drops the separators
def between[left,right,s]:
    before,_,a = s.partition[left]
    a,_,after = a.partition[right]
    return before,a,after
 
s = "bla bla blaa data lsdjfasdjöf [important notice] 'Daniweb forum' tcha tcha tchaa"
print between['','',s]
print between['[',']',s]
print between["'","'",s]
 
""" Output:
['bla bla blaa ', 'data', " lsdjfasdj\xc3\xb6f [important notice] 'Daniweb forum' tcha tcha tchaa"]
['bla bla blaa data lsdjfasdj\xc3\xb6f ', 'important notice', " 'Daniweb forum' tcha tcha tchaa"]
['bla bla blaa data lsdjfasdj\xc3\xb6f [important notice] ', 'Daniweb forum', ' tcha tcha tchaa']
"""

Add to Collection

import re

text = 'this is a text'

try:
    found = re.search['is[.+?]text', text].group[1]
except AttributeError:
    # AAA, ZZZ not found in the original string
    found = '0 wtitle' # apply your error handling
found

=> a

# To get more than 1 search
job_title = []
for i in range[0,9282]:
    text = data.work_experiences.iloc[i]
    try:
        title = re.findall[r"wtitle [.*?] wcompany",text]
    except :
        title = 'onejob'
    job_title.append[title]
    
data['job_title'] = job_title

Add to Collection

# best way
data['resume'] = data[['Resume_title', 'City', 'State', 'Description', 'work_experiences', 'Educations', 'Skills', 'Certificates', 'Additional Information']].agg[' '.join, axis=1]


# other way
df["period"] = df["Year"] + df["quarter"]
df['Period'] = df['Year'] + ' ' + df['Quarter']
df["period"] = df["Year"].astype[str] + df["quarter"] #If one [or both] of the columns are not string typed
#Beware of NaNs when doing this!
df['period'] = df[['Year', 'quarter', ...]].agg['-'.join, axis=1] #for multiple string columns
df['period'] = df[['Year', 'quarter']].apply[lambda x: ''.join[x], axis=1]
#method cat[] of the .str accessor 
df['Period'] = df.Year.str.cat[df.Quarter]
df['Period'] = df.Year.astype[str].str.cat[df.Quarter.astype[str], sep='q']
df['AllTogether'] = df['Country'].str.cat[df[['State', 'City']], sep=' - '] #add parameter na_rep to replace the NaN values with a string if have nan
columns = ['whatever', 'columns', 'you', 'choose']
df['period'] = df[columns].astype[str].sum[axis=1]

#a function
def str_join[df, sep, *cols]:
   ...:     from functools import reduce
   ...:     return reduce[lambda x, y: x.astype[str].str.cat[y.astype[str], sep=sep], 
   ...:                   [df[col] for col in cols]]
   ...: 

In [4]: df['cat'] = str_join[df, '-', 'c0', 'c1', 'c2', 'c3']

Add to Collection

import pandas as pd

data = {'Product': ['Desktop Computer','Tablet','Printer','Laptop'],
        'Price': [850,200,150,1300]
        }

df = pd.DataFrame[data, columns= ['Product', 'Price']]

df.to_csv[r'Path where you want to store the exported CSV file\File Name.csv']
# df.to_csv['file_name.csv', encoding='utf-8', index=False]
print [df]

data[['column1','column2','column3',...]].to_csv['fileNameWhereYouwantToWrite.csv']
     
df = pd.DataFrame[]
for i in range[]:
	#....
	df.appen[text]

Add to Collection

for c in df_drop.columns:
    df_drop[c] = df_drop[c].str.replace['[^\w\s]+', '']
df_drop = df_drop.astype[str]
df_drop.head[]

Add to Collection

rmsval = df.loc[:, 'c1':'c4']
def getrms[row]:  
  a = np.sqrt[sum[row**2/4]]
  return a
df['rms'] = df.apply[getrms,axis=1]
df.head[]

Add to Collection

all_filenames = glob.glob["/home/lynaza/Desktop/Quinn/lda/檢察官起訴書/*.txt"]

#return only filename [may contain not only duoi file]
 import os
 arr = os.listdir["/home/lynaza/Desktop/Quinn/lda/檢察官起訴書"]
 print[arr]



import cv2
import os
import glob

def load_images_name[path]:
    
    list_1 = glob.glob[path+'/*.tif'] # depth of 1 folder
    
    list_2 = glob.glob[path+'/*/*.tif'] # depth of 2 folder
    
    list_3 = glob.glob[path+'/*/*/*.tif']  # depth of 3 folder
    
    list_4 = glob.glob[path+'/*/*/*/*.tif']  # depth of 4 folder
    
    images_path = list_1 +list_2 +list_3 + list_4

    return images_path

images = load_images_name["/home/lynaza/Desktop/traindata/test"]

Add to Collection

//vimsky.com/zh-tw/examples/detail/python-method-regex.sub.html

Add to Collection

import pandas as pd

data = {'Product': ['Desktop Computer','Tablet','Printer','Laptop'],
        'Price': [850,200,150,1300]
        }

df = pd.DataFrame[data, columns= ['Product', 'Price']]

df.to_csv[r'Path where you want to store the exported CSV file\File Name.csv']
# df.to_csv['file_name.csv', encoding='utf-8', index=False]
print [df]

data[['column1','column2','column3',...]].to_csv['fileNameWhereYouwantToWrite.csv']
     
df = pd.DataFrame[]
for i in range[]:
	#....
	df.appen[text]

Add to Collection

from google.colab import drive
drive.mount['/content/drive/']
import sys
sys.path.insert[0,'/content/drive/MyDrive/']
train_df = pd.read_csv["/content/drive/MyDrive/train.csv"]

Add to Collection

for idx in range[num]:
    # Print the first 16 most representative topics
    print["Topic #%s:" % idx, lda_model.print_topic[idx, 6]]

Add to Collection

# //www.dataquest.io/blog/tutorial-time-series-analysis-with-pandas/
df['TIME'] =  pd.to_datetime[df['Time'],unit='s']
df_time = df.set_index['TIME']
# Add columns with year, month, and Weekday Name
df_time['Year'] = df_time.index.year
df_time['Month'] = df_time.index.month
df_time['Weekday Name'] = df_time.index.weekday_name

# Display a random sampling of 5 rows
df_time.sample[5, random_state=0]

# Visualizing time series data
sns.set[rc={'figure.figsize':[11, 4]}]

Add to Collection

#You can do it using GloVe library:

#Install it: 

!pip install glove_python

from glove import Corpus, Glove

#Creating a corpus object
corpus = Corpus[] 

#Training the corpus to generate the co-occurrence matrix which is used in GloVe
corpus.fit[lines, window=10]

glove = Glove[no_components=5, learning_rate=0.05] 
glove.fit[corpus.matrix, epochs=30, no_threads=4, verbose=True]
glove.add_dictionary[corpus.dictionary]
glove.save['glove.model']
 Save

 
 
 #for Fasttext
 from gensim.models import FastText
from gensim.test.utils import common_texts  # some example sentences
>>>
print[common_texts[0]]
['human', 'interface', 'computer']
print[len[common_texts]]
9
model = FastText[vector_size=4, window=3, min_count=1]  # instantiate
model.build_vocab[sentences=common_texts]
model.train[sentences=common_texts, total_examples=len[common_texts], epochs=10]  # train
model2 = FastText[vector_size=4, window=3, min_count=1, sentences=common_texts, epochs=10]

import numpy as np
>>>
np.allclose[model.wv['computer'], model2.wv['computer']]
True


from gensim.test.utils import datapath
>>>
corpus_file = datapath['lee_background.cor']  # absolute path to corpus
model3 = FastText[vector_size=4, window=3, min_count=1]
model3.build_vocab[corpus_file=corpus_file]  # scan over corpus to build the vocabulary
>>>
total_words = model3.corpus_total_words  # number of words in the corpus
model3.train[corpus_file=corpus_file, total_words=total_words, epochs=5]


from gensim.utils import tokenize
from gensim import utils
>>>
>>>
class MyIter:
    def __iter__[self]:
        path = datapath['crime-and-punishment.txt']
        with utils.open[path, 'r', encoding='utf-8'] as fin:
            for line in fin:
                yield list[tokenize[line]]
>>>
>>>
model4 = FastText[vector_size=4, window=3, min_count=1]
model4.build_vocab[sentences=MyIter[]]
total_examples = model4.corpus_count
model4.train[sentences=MyIter[], total_examples=total_examples, epochs=5]
from gensim.test.utils import get_tmpfile
>>>
fname = get_tmpfile["fasttext.model"]
>>>
model.save[fname]
model = FastText.load[fname]


# //radimrehurek.com/gensim/models/fasttext.html

Add to Collection

# pip
pip install camelot-py
# conda
conda install -c conda-forge camelot-py
import camelot
tables = camelot.read_pdf['foo.pdf', pages='1', flavor='lattice']
print[tables]
tables.export['foo.csv', f='csv', compress=True]
tables[0].to_csv['foo.csv']  # to a csv file
print[tables[0].df]  # to a df


# from website
import pandas as pd
simpsons = pd.read_html['//en.wikipedia.org/wiki/List_of_The_Simpsons_episodes_[seasons_1%E2%80%9320]']
# getting the first 5 rows of the table "Season 1" [second table]
simpsons[1].head[]

Add to Collection

df = df[df['resume_ontology'].str.strip[].astype[bool]]                                                                                                            

Add to Collection

cmt['time'] = pd.to_datetime[cmt['post_time']]
cmt_4 = cmt[[cmt['time'] >= '2022-02-01']]
#convert df back to string
cmt_4["time"] = cmt_4["time"].dt.strftime['%Y:%M:%D']

Add to Collection

# import pandas
import pandas as pd
   
# read csv data
df1 = pd.read_csv['Student_data.csv']
df2 = pd.read_csv['Course_enrolled.csv']
   
Right_join = pd.merge[df1, 
                      df2, 
                      on ='Name',
                      how ='right']
Right_join

Add to Collection

Similiar Collections

[Occurrence of max numbers] Write a program that reads integers, finds the largest of them, and counts its occurrences. Assume that the input ends with number 0. Suppose that you entered 3 5 2 5 5 5 0; the program finds that the largest is 5 and the occurrence count for 5 is 4 [Fibonacci Series] The Fibonacci series is a series that begins with 0 and 1 and has the property that each succeeding term is the sum of the two preceding terms. For example, the third Fibonacci number is 1 which is sum of 0 and 1. The next is 2, which is a sum of 1 + 1. Write a program that displays the first ten numbers in a Fibonacci series **5.21 [Display numbers in a pyramid pattern] Write a nested for loop that prints the following output: [Compute the greatest common divisor] Another solution for Listing 5.10 to find the greatest common divisor [GCD] of two integers n1 and n2 is as follows: First find d to be the minimum of n1 and n2, then check whether d, d-1, d-2, . . . , 2, or 1 is a divisor for both n1 and n2 in this order. The first such common divisor is the greatest common divisor for n1 and n2. Write a program that prompts the user to enter two positive integers and displays the GCD. sorting

MySQL MULTIPLES INNER JOIN How to Use EXISTS, UNIQUE, DISTINCT, and OVERLAPS in SQL Statements - dummies postgresql - SQL OVERLAPS PostgreSQL Joins: Inner, Outer, Left, Right, Natural with Examples PostgreSQL Joins: A Visual Explanation of PostgreSQL Joins PL/pgSQL Variables [ Format Dates ] The Ultimate Guide to PostgreSQL Date By Examples Data Type Formatting Functions PostgreSQL - How to calculate difference between two timestamps? | TablePlus Date/Time Functions and Operators PostgreSQL - DATEDIFF - Datetime Difference in Seconds, Days, Months, Weeks etc - SQLines CASE Statements in PostgreSQL - DataCamp SQL Optimizations in PostgreSQL: IN vs EXISTS vs ANY/ALL vs JOIN PostgreSQL DESCRIBE TABLE Quick and best way to Compare Two Tables in SQL - DWgeek.com sql - Best way to select random rows PostgreSQL - Stack Overflow PostgreSQL: Documentation: 13: 70.1. Row Estimation Examples Faster PostgreSQL Counting How to Add a Default Value to a Column in PostgreSQL - PopSQL How to Add a Default Value to a Column in PostgreSQL - PopSQL SQL Subquery - Dofactory SQL IN - SQL NOT IN - JournalDev DROP FUNCTION [Transact-SQL] - SQL Server | Microsoft Docs SQL : Multiple Row and Column Subqueries - w3resource PostgreSQL: Documentation: 9.5: CREATE FUNCTION PostgreSQL CREATE FUNCTION By Practical Examples datetime - PHP Sort a multidimensional array by element containing date - Stack Overflow database - Oracle order NULL LAST by default - Stack Overflow PostgreSQL: Documentation: 9.5: Modifying Tables PostgreSQL: Documentation: 14: SELECT postgresql - sql ORDER BY multiple values in specific order? - Stack Overflow How do I get the current unix timestamp from PostgreSQL? - Database Administrators Stack Exchange

substr[]: It takes two arguments, the starting index and number of characters to slice. substring[]: It takes two arguments, the starting index and the stopping index but it doesn't include the character at the stopping index. split[]: The split method splits a string at a specified place. includes[]: It takes a substring argument and it checks if substring argument exists in the string. includes[] returns a boolean. If a substring exist in a string, it returns true, otherwise it returns false. replace[]: takes as a parameter the old substring and a new substring. replace[]: takes as a parameter the old substring and a new substring. charAt[]: Takes index and it returns the value at that index indexOf[]: Takes a substring and if the substring exists in a string it returns the first position of the substring if does not exist it returns -1 lastIndexOf[]: Takes a substring and if the substring exists in a string it returns the last position of the substring if it does not exist it returns -1 concat[]: it takes many substrings and joins them. startsWith: it takes a substring as an argument and it checks if the string starts with that specified substring. It returns a boolean[true or false]. endsWith: it takes a substring as an argument and it checks if the string ends with that specified substring. It returns a boolean[true or false]. search: it takes a substring as an argument and it returns the index of the first match. The search value can be a string or a regular expression pattern. match: it takes a substring or regular expression pattern as an argument and it returns an array if there is match if not it returns null. Let us see how a regular expression pattern looks like. It starts with / sign and ends with / sign. repeat[]: it takes a number as argument and it returns the repeated version of the string. Concatenating array using concat indexOf:To check if an item exist in an array. If it exists it returns the index else it returns -1. lastIndexOf: It gives the position of the last item in the array. If it exist, it returns the index else it returns -1. includes:To check if an item exist in an array. If it exist it returns the true else it returns false. Array.isArray:To check if the data type is an array toString:Converts array to string join: It is used to join the elements of the array, the argument we passed in the join method will be joined in the array and return as a string. By default, it joins with a comma, but we can pass different string parameter which can be joined between the items. Slice: To cut out a multiple items in range. It takes two parameters:starting and ending position. It doesn't include the ending position. Splice: It takes three parameters:Starting position, number of times to be removed and number of items to be added. Push: adding item in the end. To add item to the end of an existing array we use the push method. pop: Removing item in the end shift: Removing one array element in the beginning of the array. unshift: Adding array element in the beginning of the array. for of loop Unlimited number of parameters in regular function Unlimited number of parameters in arrow function Expression functions are anonymous functions. After we create a function without a name and we assign it to a variable. To return a value from the function we should call the variable. Self invoking functions are anonymous functions which do not need to be called to return a value. Arrow Function Object.assign: To copy an object without modifying the original object Object.keys: To get the keys or properties of an object as an array Object.values:To get values of an object as an array Object.entries:To get the keys and values in an array hasOwnProperty: To check if a specific key or property exist in an object forEach: Iterate an array elements. We use forEach only with arrays. It takes a callback function with elements, index parameter and array itself. The index and the array optional. map: Iterate an array elements and modify the array elements. It takes a callback function with elements, index , array parameter and return a new array. Filter: Filter out items which full fill filtering conditions and return a new array reduce: Reduce takes a callback function. The call back function takes accumulator, current, and optional initial value as a parameter and returns a single value. It is a good practice to define an initial value for the accumulator value. If we do not specify this parameter, by default accumulator will get array first value. If our array is an empty array, then Javascript will throw an error every: Check if all the elements are similar in one aspect. It returns boolean find: Return the first element which satisfies the condition findIndex: Return the position of the first element which satisfies the condition some: Check if some of the elements are similar in one aspect. It returns boolean sort: The sort methods arranges the array elements either ascending or descending order. By default, the sort[] method sorts values as strings.This works well for string array items but not for numbers. If number values are sorted as strings and it give us wrong result. Sort method modify the original array. use a compare call back function inside the sort method, which return a negative, zero or positive. Whenever we sort objects in an array, we use the object key to compare. Destructing Arrays : If we like to skip on of the values in the array we use additional comma. The comma helps to omit the value at that specific index

Chủ Đề