markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Projet
%tensorflow_version 2.x import tensorflow as tf print(tf.__version__) from __future__ import absolute_import, division, print_function, unicode_literals from google.colab import files import numpy as np import tensorflow_datasets as tfds import tensorflow as tf import pandas as pd import matplotlib.pyplot as plt import...
_____no_output_____
MIT
ProjetTripAdvisor_Final.ipynb
a-essa/Sentiment-Analysis-and-Satisfaction-Prediction
Read CSV
Total_data_for_tokenizer=pd.read_csv('/content/gdrive/My Drive/Data/Total_data_for_tokenizer.csv' , sep='\t') training_set_TripAdvisor=pd.read_csv('/content/gdrive/My Drive/Data/training_set_TripAdvisor.csv' , sep='\t') test_set_TripAdvisor=pd.read_csv('/content/gdrive/My Drive/Data/test_set_TripAdvisor.csv' , sep='\t'...
_____no_output_____
MIT
ProjetTripAdvisor_Final.ipynb
a-essa/Sentiment-Analysis-and-Satisfaction-Prediction
Tokenizer
def create_dataset(dataframe): msk = np.random.rand(len(dataframe)) < 0.8 train = dataframe[msk] test = dataframe[~msk] #print(train_file_path.head) all_data = np.array(dataframe.values.tolist()) training_set = np.array(train.values.tolist()) test_set=np.array(test.values.tolist()) print("Dataset Leng...
_____no_output_____
MIT
ProjetTripAdvisor_Final.ipynb
a-essa/Sentiment-Analysis-and-Satisfaction-Prediction
Embeddings pretraining (Next Word Prediction)
def split_sentences_forward(input_set): input_sequences = [] for line in input_set: for i in range(1, len(line)): if i < 99 : n_gram_sequence = line[:i+1] else : n_gram_sequence = line[i-99:i+1] input_sequences.append(n_gram_sequence) return input_sequences def sp...
Train on 947983 samples, validate on 237895 samples Epoch 1/2 947900/947983 [============================>.] - ETA: 0s - loss: 5.7982 - accuracy: 0.1446 Epoch 00001: saving model to training_Embadding/cp-0001.ckpt 947983/947983 [==============================] - 547s 577us/sample - loss: 5.7982 - accuracy: 0.1446 - val...
MIT
ProjetTripAdvisor_Final.ipynb
a-essa/Sentiment-Analysis-and-Satisfaction-Prediction
Dataset slices
from __future__ import absolute_import, division, print_function, unicode_literals input_train_CL_sequences_1 = pad_sentences_post(input_training_set_IMDB, max_len) input_train_CL_sequences_2 = pad_sentences_post(input_training_set_TripAdvisor, max_len) input_test_CL_sequences_1 = pad_sentences_post(input_test_set_IMDB...
_____no_output_____
MIT
ProjetTripAdvisor_Final.ipynb
a-essa/Sentiment-Analysis-and-Satisfaction-Prediction
Model
BidirectionalLayer1 = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences = True)) BidirectionalLayer2 = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences = True)) GlobalMaxPool1DLayer = tf.keras.layers.GlobalMaxPool1D() DenseLayer1 = tf.keras.layers.Dense(40, kernel_regularize...
_____no_output_____
MIT
ProjetTripAdvisor_Final.ipynb
a-essa/Sentiment-Analysis-and-Satisfaction-Prediction
From saved weights
'''EmbeddingLayer = tf.keras.layers.Embedding(80008, 64) BidirectionalLayer1 = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences = True)) BidirectionalLayer2 = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences = True)) GlobalMaxPool1DLayer = tf.keras.layers.GlobalMaxPool1D() ...
_____no_output_____
MIT
ProjetTripAdvisor_Final.ipynb
a-essa/Sentiment-Analysis-and-Satisfaction-Prediction
Validation
from sklearn.metrics import mean_squared_error import nltk nltk.download("stopwords") nltk.download("punkt") from nltk.corpus import stopwords from nltk.tokenize import word_tokenize nltk.download('wordnet') from nltk.stem import WordNetLemmatizer def clean_set(set_len): stop_words = list(stopwords.words('eng...
_____no_output_____
MIT
ProjetTripAdvisor_Final.ipynb
a-essa/Sentiment-Analysis-and-Satisfaction-Prediction
NLTK Sentence and Word Tokenization
from nltk.tokenize import sent_tokenize, word_tokenize EXAMPLE_TEXT = "Hello Mr. Smith, how are you doing today? The weather is great, and Python is awesome. The sky is pinkish-blue. You shouldn't eat cardboard." # Sentence Tokenization print(sent_tokenize(EXAMPLE_TEXT)) # Word Tokenization print(word_tokenize(EXAMPLE_...
['Hello', 'Mr.', 'Smith', ',', 'how', 'are', 'you', 'doing', 'today', '?', 'The', 'weather', 'is', 'great', ',', 'and', 'Python', 'is', 'awesome', '.', 'The', 'sky', 'is', 'pinkish-blue', '.', 'You', 'should', "n't", 'eat', 'cardboard', '.']
MIT
NLTK/NLTK.ipynb
jimit105/Python-Libraries
Stopwords
from nltk.corpus import stopwords # Printing all stopwords (english) set(stopwords.words('english')) example_sent = "This is a sample sentence, showing off the stop words filtration." stop_words = set(stopwords.words('english')) word_tokens = word_tokenize(example_sent) filtered_sentence = [w for w in word_tokens if no...
['This', 'is', 'a', 'sample', 'sentence', ',', 'showing', 'off', 'the', 'stop', 'words', 'filtration', '.'] ['This', 'sample', 'sentence', ',', 'showing', 'stop', 'words', 'filtration', '.']
MIT
NLTK/NLTK.ipynb
jimit105/Python-Libraries
Stemming words
# Porter Stemmer is a stemming algorithm from nltk.stem import PorterStemmer from nltk.tokenize import sent_tokenize, word_tokenize ps = PorterStemmer() example_words = ["python","pythoner","pythoning","pythoned","pythonly"] for w in example_words: print(ps.stem(w)) new_text = "It is important to by very pythonly ...
It is import to by veri pythonli while you are python with python . all python have python poorli at least onc .
MIT
NLTK/NLTK.ipynb
jimit105/Python-Libraries
Part of Speech Tagging POS tag list:CC coordinating conjunction CD cardinal digit DT determiner EX existential there (like: "there is" ... think of it like "there exists") FW foreign word IN preposition/subordinating conjunction JJ adjective 'big' JJR adjective, comparative 'bigger' JJS adjective, superlative...
import nltk from nltk.corpus import state_union from nltk.tokenize import PunktSentenceTokenizer # Create training and testing data train_text = state_union.raw('2005-GWBush.txt') sample_text = state_union.raw('2006-GWBush.txt') # Train Punkt tokenizer custom_sent_tokenizer = PunktSentenceTokenizer(train_text) # Actual...
[('PRESIDENT', 'NNP'), ('GEORGE', 'NNP'), ('W.', 'NNP'), ('BUSH', 'NNP'), ("'S", 'POS'), ('ADDRESS', 'NNP'), ('BEFORE', 'IN'), ('A', 'NNP'), ('JOINT', 'NNP'), ('SESSION', 'NNP'), ('OF', 'IN'), ('THE', 'NNP'), ('CONGRESS', 'NNP'), ('ON', 'NNP'), ('THE', 'NNP'), ('STATE', 'NNP'), ('OF', 'IN'), ('THE', 'NNP'), ('UNION', '...
MIT
NLTK/NLTK.ipynb
jimit105/Python-Libraries
Lemmatizing > A very similar operation to stemming is called lemmatizing. The major difference between these is, as you saw earlier, stemming can often create non-existent words, whereas lemmas are actual words. > So, your root stem, meaning the word you end up with, is not something you can just look up in a diction...
from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() print(lemmatizer.lemmatize("cats")) print(lemmatizer.lemmatize("cacti")) print(lemmatizer.lemmatize("geese")) print(lemmatizer.lemmatize("rocks")) print(lemmatizer.lemmatize("python")) print(lemmatizer.lemmatize("better", pos="a")) print(lemmatiz...
cat cactus goose rock python good best run run
MIT
NLTK/NLTK.ipynb
jimit105/Python-Libraries
Corpora> The NLTK corpus is a massive dump of all kinds of natural language data sets
# Opening the Gutenberg Bible, and reading the first few lines from nltk.tokenize import sent_tokenize, PunktSentenceTokenizer from nltk.corpus import gutenberg #sample text sample = gutenberg.raw('bible-kjv.txt') tok = sent_tokenize(sample) for x in range(5): print(tok[x])
[The King James Bible] The Old Testament of the King James Bible The First Book of Moses: Called Genesis 1:1 In the beginning God created the heaven and the earth. 1:2 And the earth was without form, and void; and darkness was upon the face of the deep. And the Spirit of God moved upon the face of the waters. 1:3 ...
MIT
NLTK/NLTK.ipynb
jimit105/Python-Libraries
Wordnet> Wordnet is a collection of words, definitions, examples of their use, synonyms, antonyms, and more.
# Import wordnet from nltk.corpus import wordnet # use the term "program" to find synsets syns = wordnet.synsets('program') print(syns) #Print first synset print(syns[0].name()) # Print only the word print(syns[0].lemmas()[0].name()) # Definition for that first synset print(syns[0].definition()) # Examples of the word...
0.9090909090909091 0.6956521739130435 0.32
MIT
NLTK/NLTK.ipynb
jimit105/Python-Libraries
1) CSV Data File Analysis
from os import path fname = path.expanduser('track.csv')
_____no_output_____
MIT
2_Data_Analysis/jogging_ex/pandas_jogging_ex.ipynb
TheManohar/DSci_Pro
CSV File Info
!ls -lh "$fname" path.getsize(fname) path.getsize(fname) / (1<<10) !head "$fname" with open(fname) as fp: for lnum, line in enumerate(fp): if lnum > 10: break print(line[:-1]) !wc -l "$fname" with open(fname) as fp: print(sum(1 for line in fp))
741
MIT
2_Data_Analysis/jogging_ex/pandas_jogging_ex.ipynb
TheManohar/DSci_Pro
2) Parse Time Series
import pandas as pd df = pd.read_csv(fname) len(df) df.columns df.info() df.head() df.dtypes
_____no_output_____
MIT
2_Data_Analysis/jogging_ex/pandas_jogging_ex.ipynb
TheManohar/DSci_Pro
Parse Dates
df = pd.read_csv(fname, parse_dates=['time']) df.dtypes
_____no_output_____
MIT
2_Data_Analysis/jogging_ex/pandas_jogging_ex.ipynb
TheManohar/DSci_Pro
3) Access Rows & Columns Data
df['lat'].head() df.lat.head() df[['lat', 'lng']].head() df['lat'][0] df.loc[0] df.loc[2:7] df[['lat', 'lng']][2:7] df.index
_____no_output_____
MIT
2_Data_Analysis/jogging_ex/pandas_jogging_ex.ipynb
TheManohar/DSci_Pro
NumPy`.loc[]` example
import numpy as np df1 = pd.DataFrame(np.arange(10).reshape((5,2)), columns=['x', 'y'], index=['a', 'b', 'c', 'd', 'e']) df1 df1.loc['a'] df1.loc['b': 'd']
_____no_output_____
MIT
2_Data_Analysis/jogging_ex/pandas_jogging_ex.ipynb
TheManohar/DSci_Pro
Set Index
df.index df.index = df['time'] df.index
_____no_output_____
MIT
2_Data_Analysis/jogging_ex/pandas_jogging_ex.ipynb
TheManohar/DSci_Pro
Locate Specific Time Data
df.loc['2015-08-20 04:18:54'] # all masures in this particular minute df.loc['2015-08-20 03:48']
_____no_output_____
MIT
2_Data_Analysis/jogging_ex/pandas_jogging_ex.ipynb
TheManohar/DSci_Pro
Timezone Localization
# pytz module contains all timezone information import pytz ts = df.index[0] ts.tz_localize(pytz.UTC) ts.tz_localize(pytz.UTC).tz_convert(pytz.timezone('Asia/Jerusalem')) df.index = df.index.tz_localize(pytz.UTC).tz_convert(pytz.timezone('Asia/Jerusalem')) df.index[:10] %pwd
_____no_output_____
MIT
2_Data_Analysis/jogging_ex/pandas_jogging_ex.ipynb
TheManohar/DSci_Pro
4) Import Custom Modules
import geo import sys sys.path ??geo from geo import circle_dist lat1, lng1 = df.iloc[0].lat, df.iloc[0].lng lat2, lng2 = df.iloc[1].lat, df.iloc[1].lng circle_dist(lat1, lng1, lat2, lng2)
_____no_output_____
MIT
2_Data_Analysis/jogging_ex/pandas_jogging_ex.ipynb
TheManohar/DSci_Pro
5) Calculate Speed (geo) pandas.`shift()` example
s = pd.Series(np.arange(5)) s s.shift() s.shift(-1)
_____no_output_____
MIT
2_Data_Analysis/jogging_ex/pandas_jogging_ex.ipynb
TheManohar/DSci_Pro
Calculate Circle Distance of Data
dist = circle_dist(df['lat'], df['lng'], df['lat'].shift(), df['lng'].shift()) dist[:10] dist.sum() dt = df['time'] - df['time'].shift() dt[:10] # NaT means Not a Time dt.sum() dt[1].total_seconds() dt[1] / np.timedelta64(1, 'h') dt[1].total_seconds()/3600 speed = dist / (dt / np.timedelta64(1, 'h')) speed[:10] df['dis...
_____no_output_____
MIT
2_Data_Analysis/jogging_ex/pandas_jogging_ex.ipynb
TheManohar/DSci_Pro
6) Display Speed Box Plot
%matplotlib inline speed1m.plot() import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (10, 6) plt.style.available plt.style.use('seaborn-whitegrid') speed1m.plot() speed1m.plot.box()
_____no_output_____
MIT
2_Data_Analysis/jogging_ex/pandas_jogging_ex.ipynb
TheManohar/DSci_Pro
SMOOTHING (LOWPASS) SPATIAL FILTERS
import cv2 import matplotlib.pyplot as plt import numpy as np
_____no_output_____
MIT
SMOOTHING (LOWPASS) SPATIAL FILTERS.ipynb
MTandHJ/digital-image-processing
FILTERSfilters实际上就是通过一些特殊的kernel $w$ 对图片进行如下操作:$$g(x, y) = \sum_{s=-a}^a \sum_{t=-b}^b w(s, t) f(x+s, y+t), \: x = 1,2,\cdots, M, \: y = 1, 2,\cdots N.$$其中$w(s, t) \in \mathbb{R}^{m \times n}, m=2a+1, n = 2b+1$.注: 一般来说kernel的边是奇数, 这样可以确定唯一的中心, 但是偶数其实也是可以的.实际上, 上面可以转换成卷积的形式:$$(w * f) (x, y) = \sum_{s=-a}^a \sum_{t=-b}^...
img = cv2.imread("./pics/alphabeta.png") img.shape img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 由于是截图, 先转成灰度图 plt.imshow(img, cmap='gray') # 或者等价地用 cv2.blur(img, (m, n)) kernels = [np.ones((i, i)) / (i * i) for i in [3, 11, 21]] imgs_smoothed = [cv2.filter2D(img, -1, kernel) for kernel in kernels] fig, axes = plt.subp...
_____no_output_____
MIT
SMOOTHING (LOWPASS) SPATIAL FILTERS.ipynb
MTandHJ/digital-image-processing
Lowpass Gaussian Filter Kernels即$$w(s, t) = G(s, t) = K e^{-\frac{s^2+t^2}{2\sigma^2}},$$高斯分布的特点是绝大部分集中于$(-3\sigma, +3\sigma)$之间, 故一般$w$的大小选择为$(-6\sigma, +6\sigma)$, 需要注意的是, $\sigma$的选择和图片的大小息息相关.
imgs_smoothed = [cv2.GaussianBlur(img, ksize=ksize, sigmaX=sigma) for (ksize, sigma) in [((5, 5), 1), ((21, 21), 3.5), ((43, 43), 7)]] fig, axes = plt.subplots(1, 4) axes[0].imshow(img, cmap='gray') axes[0].set_title("raw") axes[1].imshow(imgs_smoothed[0], cmap="gray") axes[1].set_title("5x5, 1") axes[2].imshow(imgs_sm...
_____no_output_____
MIT
SMOOTHING (LOWPASS) SPATIAL FILTERS.ipynb
MTandHJ/digital-image-processing
Order-Statistic (Nonlinear) Filters即$g(x, y)$由$(x, y)$周围的点的一个某个顺序的值代替, 比如median.
imgs_smoothed = [cv2.medianBlur(img, ksize=ksize) for ksize in [3, 7, 15]] fig, axes = plt.subplots(1, 4) axes[0].imshow(img, cmap='gray') axes[0].set_title("raw") axes[1].imshow(imgs_smoothed[0], cmap="gray") axes[1].set_title("3x3") axes[2].imshow(imgs_smoothed[1], cmap="gray") axes[2].set_title("7x7") axes[3].imshow...
_____no_output_____
MIT
SMOOTHING (LOWPASS) SPATIAL FILTERS.ipynb
MTandHJ/digital-image-processing
Destination's street density INDEX This code allows you to estimate:The street density INDEX at the DESTINATION for only one origin point or for a set of origins. The street density is estimated base on a selection of arcs contained within a 600m buffer around each destination. All the arcs selected in relation to ea...
%matplotlib inline import numpy as np import pandas as pd import geopandas as gpd import matplotlib.pyplot as plt import matplotlib as mpl import csv import math print ("it works")
it works
MIT
Code/108_D_end_street density_analysis.ipynb
Rise-group/database_cyclists_medellin
Example for only one route
route = 1002 db = gpd.read_file('../Shapes/end_arcs600/R' +"%s" % (route) +'_end_arcs600.shp') print (db.crs) db.head() db.info() db.plot() radio = 0.6 area = 3.14159265358979 * radio**2 D_Lstreet = (db['Long']).sum()/1000 D_streetdens = D_Lstreet / area print ("D_Lstreet:" + str(D_Lstreet)) print ("D_streetdens:" + s...
_____no_output_____
MIT
Code/108_D_end_street density_analysis.ipynb
Rise-group/database_cyclists_medellin
Street density estimated for All routes The code requires the list of the origin points associated to all the routes. This list is located in the Tables folder. If you move this file out of this folder, please modify the code.
routes = np.loadtxt('../Tables/Routes.txt',dtype='str') for i in routes: db = gpd.read_file('../Shapes/end_arcs600/R' +"%s" % (i) +'_end_arcs600.shp') radio = 0.6 area = 3.14159265358979 * radio**2 D_Lstreet = (db['Long']).sum()/1000 D_streetdens = D_Lstreet / area results = pd.DataFrame ({ ...
_____no_output_____
MIT
Code/108_D_end_street density_analysis.ipynb
Rise-group/database_cyclists_medellin
This part of the code summarizes the intersection index related to each origin in only one table. Please copy it to a text file and save.
print ('route,D_Lstreet,D_sttdens') for i in routes: df=np.loadtxt('../Tables/OUT/R' +"%s" %(i)+'_end_sd600.txt', delimiter=',',skiprows=1) print ((df[0]),(df[1]),(df[2]))
route,D_Lstreet,D_sttdens 1002.0 24.733079128306873 21.868843339739048 1006.0 26.1401686196655 23.112983605974527 1009.0 16.660137417108547 14.73079568068372 1050.0 16.93572274099809 14.974466605909287 1052.0 21.618809667095352 19.11522456822823 1079.0 25.1494328077544 22.236980818397786 1100.0 24.85527662835564 21.976...
MIT
Code/108_D_end_street density_analysis.ipynb
Rise-group/database_cyclists_medellin
[Day 15](https://adventofcode.com/2020/day/15): Rambunctious Recitation
data = 0, 20, 7, 16, 1, 18, 15 init = {d: i for i, d in enumerate(data, 1)} def number_spoken(turns, n=data[-1], l=len(data)): prev = init.copy() for i in range(l, turns): prev[n], n = i, i - prev.get(n, i) return n
_____no_output_____
MIT
solutions/15.ipynb
egnha/AoC-2020
Part 1
assert 1025 == number_spoken(2020)
_____no_output_____
MIT
solutions/15.ipynb
egnha/AoC-2020
Part 2
assert 129262 == number_spoken(30000000)
_____no_output_____
MIT
solutions/15.ipynb
egnha/AoC-2020
Regular Expression Exercises* Debugger: When debugging regular expressions, the best tool is [Regex101](https://regex101.com/). This is an interactive tool that let's you visualize a regular expression in action.* Tutorial: I tend to like RealPython's tutorials, here is their's on [Regular Expressions](https://realpyt...
import re
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
1. Introduction**a)** Check whether the given strings contain `0xB0`. Display a boolean result as shown below.
line1 = 'start address: 0xA0, func1 address: 0xC0' line2 = 'end address: 0xFF, func2 address: 0xB0' assert bool(re.search(r'', line1)) == False assert bool(re.search(r'', line2)) == True
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**b)** Replace all occurrences of `5` with `five` for the given string.
ip = 'They ate 5 apples and 5 oranges' assert re.sub() == 'They ate five apples and five oranges'
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**c)** Replace first occurrence of `5` with `five` for the given string.
ip = 'They ate 5 apples and 5 oranges' assert re.sub() == 'They ate five apples and 5 oranges'
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**d)** For the given list, filter all elements that do *not* contain `e`.
items = ['goal', 'new', 'user', 'sit', 'eat', 'dinner'] assert [w for w in items if not re.search()] == ['goal', 'sit']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**e)** Replace all occurrences of `note` irrespective of case with `X`.
ip = 'This note should not be NoTeD' assert re.sub() == 'This X should not be XD'
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**f)** Check if `at` is present in the given byte input data.
ip = 'tiger imp goat' assert bool(re.search()) == True
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**g)** For the given input string, display all lines not containing `start` irrespective of case.
para = '''good start Start working on that project you always wanted stars are shining brightly hi there start and try to finish the book bye''' pat = re.compile() ##### add your solution here for line in para.split('\n'): if not pat.search(line): print(line) """project you always wanted stars are sh...
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**h)** For the given list, filter all elements that contains either `a` or `w`.
items = ['goal', 'new', 'user', 'sit', 'eat', 'dinner'] ##### add your solution here assert [w for w in items if re.search() or re.search()] == ['goal', 'new', 'eat']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**i)** For the given list, filter all elements that contains both `e` and `n`.
items = ['goal', 'new', 'user', 'sit', 'eat', 'dinner'] ##### add your solution here assert [w for w in items if re.search() and re.search()] == ['new', 'dinner']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**j)** For the given string, replace `0xA0` with `0x7F` and `0xC0` with `0x1F`.
ip = 'start address: 0xA0, func1 address: 0xC0' ##### add your solution here assert ___ == 'start address: 0x7F, func1 address: 0x1F'
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
2. Anchors**a)** Check if the given strings start with `be`.
line1 = 'be nice' line2 = '"best!"' line3 = 'better?' line4 = 'oh no\nbear spotted' pat = re.compile() ##### add your solution here assert bool(pat.search(line1)) == True assert bool(pat.search(line2)) == False assert bool(pat.search(line3)) == True assert bool(pat.search(line4)) == False
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**b)** For the given input string, change only whole word `red` to `brown`
words = 'bred red spread credible' assert re.sub() == 'bred brown spread credible'
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**c)** For the given input list, filter all elements that contains `42` surrounded by word characters.
words = ['hi42bye', 'nice1423', 'bad42', 'cool_42a', 'fake4b'] assert [w for w in words if re.search()] == ['hi42bye', 'nice1423', 'cool_42a']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**d)** For the given input list, filter all elements that start with `den` or end with `ly`.
items = ['lovely', '1\ndentist', '2 lonely', 'eden', 'fly\n', 'dent'] assert [e for e in items if ] == ['lovely', '2 lonely', 'dent']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**e)** For the given input string, change whole word `mall` to `1234` only if it is at the start of a line.
para = ''' ball fall wall tall mall call ball pall wall mall ball fall mallet wallet malls''' assert re.sub() == """ball fall wall tall 1234 call ball pall wall mall ball fall mallet wallet malls"""
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**f)** For the given list, filter all elements having a line starting with `den` or ending with `ly`.
items = ['lovely', '1\ndentist', '2 lonely', 'eden', 'fly\nfar', 'dent'] ##### add your solution here assert ___ == ['lovely', '1\ndentist', '2 lonely', 'fly\nfar', 'dent']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**g)** For the given input list, filter all whole elements `12\nthree` irrespective of case.
items = ['12\nthree\n', '12\nThree', '12\nthree\n4', '12\nthree'] ##### add your solution here assert ___ == ['12\nThree', '12\nthree']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**h)** For the given input list, replace `hand` with `X` for all elements that start with `hand` followed by at least one word character.
items = ['handed', 'hand', 'handy', 'unhanded', 'handle', 'hand-2'] ##### add your solution here assert ___ == ['Xed', 'hand', 'Xy', 'unhanded', 'Xle', 'hand-2']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**i)** For the given input list, filter all elements starting with `h`. Additionally, replace `e` with `X` for these filtered elements.
items = ['handed', 'hand', 'handy', 'unhanded', 'handle', 'hand-2'] ##### add your solution here assert ___ == ['handXd', 'hand', 'handy', 'handlX', 'hand-2']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
3. Alternation and Grouping**a)** For the given input list, filter all elements that start with `den` or end with `ly`
items = ['lovely', '1\ndentist', '2 lonely', 'eden', 'fly\n', 'dent'] ##### add your solution here assert ___ == ['lovely', '2 lonely', 'dent']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**b)** For the given list, filter all elements having a line starting with `den` or ending with `ly`.
items = ['lovely', '1\ndentist', '2 lonely', 'eden', 'fly\nfar', 'dent'] ##### add your solution here assert ___ == ['lovely', '1\ndentist', '2 lonely', 'fly\nfar', 'dent']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**c)** For the given input strings, replace all occurrences of `removed` or `reed` or `received` or `refused` with `X`.
s1 = 'creed refuse removed read' s2 = 'refused reed redo received' pat = re.compile() ##### add your solution here assert pat.sub('X', s1) == 'cX refuse X read' assert pat.sub('X', s2) == 'X X redo X'
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**d)** For the given input strings, replace all matches from the list `words` with `A`.
s1 = 'plate full of slate' s2 = "slated for later, don't be late" words = ['late', 'later', 'slated'] pat = re.compile() ##### add your solution here assert pat.sub('A', s1) == 'pA full of sA' assert pat.sub('A', s2) == "A for A, don't be A"
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**e)** Filter all whole elements from the input list `items` based on elements listed in `words`.
items = ['slate', 'later', 'plate', 'late', 'slates', 'slated '] words = ['late', 'later', 'slated'] pat = re.compile() ##### add your solution here ##### add your solution here assert ___ == ['later', 'late']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
4. Escaping metacharacters**a)** Transform the given input strings to the expected output using same logic on both strings.
str1 = '(9-2)*5+qty/3' str2 = '(qty+4)/2-(9-2)*5+pq/4' ##### add your solution here for str1 assert ___ == '35+qty/3' ##### add your solution here for str2 assert ___ == '(qty+4)/2-35+pq/4'
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**b)** Replace `(4)\|` with `2` only at the start or end of given input strings.
s1 = r'2.3/(4)\|6 foo 5.3-(4)\|' s2 = r'(4)\|42 - (4)\|3' s3 = 'two - (4)\\|\n' pat = re.compile() ##### add your solution here assert pat.sub('2', s1) == '2.3/(4)\\|6 foo 5.3-2' assert pat.sub('2', s2) == '242 - (4)\\|3' assert pat.sub('2', s3) == 'two - (4)\\|\n'
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**c)** Replace any matching element from the list `items` with `X` for given the input strings. Match the elements from `items` literally. Assume no two elements of `items` will result in any matching conflict.
items = ['a.b', '3+n', r'x\y\z', 'qty||price', '{n}'] pat = re.compile() ##### add your solution here assert pat.sub('X', '0a.bcd') == '0Xcd' assert pat.sub('X', 'E{n}AMPLE') == 'EXAMPLE' assert pat.sub('X', r'43+n2 ax\y\ze') == '4X2 aXe'
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**d)** Replace backspace character `\b` with a single space character for the given input string.
ip = '123\b456' ip assert re.sub() == '123 456'
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**e)** Replace all occurrences of `\e` with `e`.
ip = r'th\er\e ar\e common asp\ects among th\e alt\ernations' assert re.sub() == 'there are common aspects among the alternations'
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**f)** Replace any matching item from the list `eqns` with `X` for given the string `ip`. Match the items from `eqns` literally.
ip = '3-(a^b)+2*(a^b)-(a/b)+3' eqns = ['(a^b)', '(a/b)', '(a^b)+2'] ##### add your solution here assert pat.sub('X', ip) == '3-X*X-X+3'
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
5. Dot metacharacter and QuantifiersSince `.` metacharacter doesn't match newline character by default, assume that the input strings in the following exercises will not contain newline characters.**a)** Replace `42//5` or `42/5` with `8` for the given input.
ip = 'a+42//5-c pressure*3+42/5-14256' assert re.sub() == 'a+8-c pressure*3+8-14256'
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**b)** For the list `items`, filter all elements starting with `hand` and ending with at most one more character or `le`.
items = ['handed', 'hand', 'handled', 'handy', 'unhand', 'hands', 'handle'] ##### add your solution here assert ___ == ['hand', 'handy', 'hands', 'handle']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**c)** Use `re.split` to get the output as shown for the given input strings.
eqn1 = 'a+42//5-c' eqn2 = 'pressure*3+42/5-14256' eqn3 = 'r*42-5/3+42///5-42/53+a' ##### add your solution here for eqn1 assert ___ == ['a+', '-c'] ##### add your solution here for eqn2 assert ___ == ['pressure*3+', '-14256'] ##### add your solution here for eqn3 assert ___ == ['r*42-5/3+42///5-', '3+a']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**d)** For the given input strings, remove everything from the first occurrence of `i` till end of the string.
s1 = 'remove the special meaning of such constructs' s2 = 'characters while constructing' pat = re.compile() ##### add your solution here assert pat.sub('', s1) == 'remove the spec' assert pat.sub('', s2) == 'characters wh'
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**e)** For the given strings, construct a RE to get output as shown.
str1 = 'a+b(addition)' str2 = 'a/b(division) + c%d(#modulo)' str3 = 'Hi there(greeting). Nice day(a(b)' remove_parentheses = re.compile() ##### add your solution here assert remove_parentheses.sub('', str1) == 'a+b' assert remove_parentheses.sub('', str2) == 'a/b + c%d' assert remove_parentheses.sub('', str3) == ...
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**f)** Correct the given RE to get the expected output.
words = 'plink incoming tint winter in caution sentient' change = re.compile(r'int|in|ion|ing|inco|inter|ink') # wrong output assert change.sub('X', words) == 'plXk XcomXg tX wXer X cautX sentient' # expected output change = re.compile() ##### add your solution here assert change.sub('X', words) == 'plX XmX tX ...
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**g)** For the given greedy quantifiers, what would be the equivalent form using `{m,n}` representation?* `?` is same as* `*` is same as* `+` is same as**h)** `(a*|b*)` is same as `(a|b)*` — True or False?**i)** For the given input strings, remove everything from the first occurrence of `test` (irrespective of case) ti...
s1 = 'this is a Test' s2 = 'always test your RE for corner cases' s3 = 'a TEST of skill tests?' pat = re.compile() ##### add your solution here assert pat.sub('', s1) == 'this is a Test' assert pat.sub('', s2) == 'always ' assert pat.sub('', s3) == 'a '
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**j)** For the input list `words`, filter all elements starting with `s` and containing `e` and `t` in any order.
words = ['sequoia', 'subtle', 'exhibit', 'asset', 'sets', 'tests', 'site'] ##### add your solution here assert ___ == ['subtle', 'sets', 'site']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**k)** For the input list `words`, remove all elements having less than `6` characters.
words = ['sequoia', 'subtle', 'exhibit', 'asset', 'sets', 'tests', 'site'] ##### add your solution here assert ___ == ['sequoia', 'subtle', 'exhibit']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**l)** For the input list `words`, filter all elements starting with `s` or `t` and having a maximum of `6` characters.
words = ['sequoia', 'subtle', 'exhibit', 'asset', 'sets', 'tests', 'site'] ##### add your solution here assert ___ == ['subtle', 'sets', 'tests', 'site']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**m)** Can you reason out why this code results in the output shown? The aim was to remove all `` patterns but not the `` ones. The expected result was `'a 1 b 2 c'`.
ip = 'a<apple> 1<> b<bye> 2<> c<cat>' assert re.sub(r'<.+?>', '', ip) == 'a 1 2'
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**n)** Use `re.split` to get the output as shown below for given input strings.
s1 = 'go there // "this // that"' s2 = 'a//b // c//d e//f // 4//5' s3 = '42// hi//bye//see // carefully' pat = re.compile() ##### add your solution here assert pat.split() == ['go there', '"this // that"'] assert pat.split() == ['a//b', 'c//d e//f // 4//5'] assert pat.split() == ['42// hi//bye//see', 'carefull...
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
6. Working with matched portions**a)** For the given strings, extract the matching portion from first `is` to last `t`.
str1 = 'This the biggest fruit you have seen?' str2 = 'Your mission is to read and practice consistently' pat = re.compile() ##### add your solution here ##### add your solution here for str1 assert ___ == 'is the biggest fruit' ##### add your solution here for str2 assert ___ == 'ission is to read and practice c...
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**b)** Find the starting index of first occurrence of `is` or `the` or `was` or `to` for the given input strings.
s1 = 'match after the last newline character' s2 = 'and then you want to test' s3 = 'this is good bye then' s4 = 'who was there to see?' pat = re.compile() ##### add your solution here ##### add your solution here for s1 assert ___ == 12 ##### add your solution here for s2 assert ___ == 4 ##### add your solution...
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**c)** Find the starting index of last occurrence of `is` or `the` or `was` or `to` for the given input strings.
s1 = 'match after the last newline character' s2 = 'and then you want to test' s3 = 'this is good bye then' s4 = 'who was there to see?' pat = re.compile() ##### add your solution here ##### add your solution here for s1 assert ___ == 12 ##### add your solution here for s2 assert ___ == 18 ##### add your solutio...
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**d)** The given input string contains `:` exactly once. Extract all characters after the `:` as output.
ip = 'fruits:apple, mango, guava, blueberry' ##### add your solution here assert ___ == 'apple, mango, guava, blueberry'
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**e)** The given input strings contains some text followed by `-` followed by a number. Replace that number with its `log` value using `math.log()`.
s1 = 'first-3.14' s2 = 'next-123' pat = re.compile() ##### add your solution here import math assert pat.sub() == 'first-1.144222799920162' assert pat.sub() == 'next-4.812184355372417'
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**f)** Replace all occurrences of `par` with `spar`, `spare` with `extra` and `park` with `garden` for the given input strings.
str1 = 'apartment has a park' str2 = 'do you have a spare cable' str3 = 'write a parser' ##### add your solution here assert pat.sub() == 'aspartment has a garden' assert pat.sub() == 'do you have a extra cable' assert pat.sub() == 'write a sparser'
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**g)** Extract all words between `(` and `)` from the given input string as a list. Assume that the input will not contain any broken parentheses.
ip = 'another (way) to reuse (portion) matched (by) capture groups' assert re.findall() == ['way', 'portion', 'by']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**h)** Extract all occurrences of ``, provided there is at least one character in between ``.
ip = 'a<apple> 1<> b<bye> 2<> c<cat>' assert re.findall() == ['<apple>', '<> b<bye>', '<> c<cat>']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**i)** Use `re.findall` to get the output as shown below for the given input strings. Note the characters used in the input strings carefully.
row1 = '-2,5 4,+3 +42,-53 4356246,-357532354 ' row2 = '1.32,-3.14 634,5.63 63.3e3,9907809345343.235 ' pat = re.compile() ##### add your solution here assert pat.findall(row1) == [('-2', '5'), ('4', '+3'), ('+42', '-53'), ('4356246', '-357532354')] pat.findall(row2) == [('1.32', '-3.14'), ('634', '5.63'), ('63.3...
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**j)** This is an extension to previous question.* For `row1`, find the sum of integers of each tuple element. For example, sum of `-2` and `5` is `3`.* For `row2`, find the sum of floating-point numbers of each tuple element. For example, sum of `1.32` and `-3.14` is `-1.82`.
row1 = '-2,5 4,+3 +42,-53 4356246,-357532354 ' row2 = '1.32,-3.14 634,5.63 63.3e3,9907809345343.235 ' # should be same as previous question pat = re.compile() ##### add your solution here ##### add your solution here for row1 assert ___ == [3, 7, -11, -353176108] ##### add your solution here for row2 assert __...
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**k)** Use `re.split` to get the output as shown below.
ip = '42:no-output;1000:car-truck;SQEX49801' assert re.split() == ['42', 'output', '1000', 'truck', 'SQEX49801']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**l)** For the given list of strings, change the elements into a tuple of original element and number of times `t` occurs in that element.
words = ['sequoia', 'attest', 'tattletale', 'asset'] ##### add your solution here assert ___ == [('sequoia', 0), ('attest', 3), ('tattletale', 4), ('asset', 1)]
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**m)** The given input string has fields separated by `:`. Each field contains four uppercase alphabets followed optionally by two digits. Ignore the last field, which is empty. See [docs.python: Match.groups](https://docs.python.org/3/library/re.htmlre.Match.groups) and use `re.finditer` to get the output as shown bel...
ip = 'TWXA42:JWPA:NTED01:' ##### add your solution here assert ___ == [('TWXA', '42'), ('JWPA', 'NA'), ('NTED', '01')]
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
>![info](../images/info.svg) Note that this is different from `re.findall` which will just give empty string instead of `None` when a capture group doesn't participate.**n)** Convert the comma separated strings to corresponding `dict` objects as shown below.
row1 = 'name:rohan,maths:75,phy:89,' row2 = 'name:rose,maths:88,phy:92,' pat = re.compile() ##### add your solution here ##### add your solution here for row1 assert ___ == {'name': 'rohan', 'maths': '75', 'phy': '89'} ##### add your solution here for row2 assert ___ == {'name': 'rose', 'maths': '88', 'phy': '92...
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
7. Character class**a)** For the list `items`, filter all elements starting with `hand` and ending with `s` or `y` or `le`.
items = ['-handy', 'hand', 'handy', 'unhand', 'hands', 'handle'] ##### add your solution here assert ___ == ['handy', 'hands', 'handle']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**b)** Replace all whole words `reed` or `read` or `red` with `X`.
ip = 'redo red credible :read: rod reed' ##### add your solution here assert ___ == 'redo X credible :X: rod X'
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**c)** For the list `words`, filter all elements containing `e` or `i` followed by `l` or `n`. Note that the order mentioned should be followed.
words = ['surrender', 'unicorn', 'newer', 'door', 'empty', 'eel', 'pest'] ##### add your solution here assert ___ == ['surrender', 'unicorn', 'eel']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects
**d)** For the list `words`, filter all elements containing `e` or `i` and `l` or `n` in any order.
words = ['surrender', 'unicorn', 'newer', 'door', 'empty', 'eel', 'pest'] ##### add your solution here assert ___ == ['surrender', 'unicorn', 'newer', 'eel']
_____no_output_____
MIT
Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb
ithakker/CISC367-Projects