markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Connection You use a connection.Session to interact with the Ovaiton REST API. Use the connect method to create an authenticated Session. You can provide your Ovation password with the password= parameter, but please keep your Ovation password secure. Don't put your password in your source code. It's much better to let...
session = connect(input('Email: '), org=int(input("Organization (enter for default): ") or 0))
examples/attributes-and-annotations.ipynb
physion/ovation-python
gpl-3.0
Attributes Ovation entities have an attributes object for user data. For example, the Ovation web app uses the attributes object to store the name of a Folder or File. You can see the names of these 'built-in' attributes for each entity at https://api.ovation.io/index.html. You can update the attributes of an entity b...
project_id = input('Project UUID: ') project = session.get(session.path('projects', id=project_id)) pprint(project) # Add a new attribute project.attributes.my_attribute = 'Wow!' # PUT the entity to save it project = session.put(project.links.self, entity=project) pprint(project)
examples/attributes-and-annotations.ipynb
physion/ovation-python
gpl-3.0
You can delete attributes by removing them from the attributes object.
# Remove an attribute del project.attributes['my_attribute'] # PUT the entity to save it project = session.put(project.links.self, entity=project)
examples/attributes-and-annotations.ipynb
physion/ovation-python
gpl-3.0
Annotations Unlike attributes which must have a single value for an entity, annotations any user to add their own information to an entity. User annotations are kept separate, so one user's annotation can't interfere with an other user's. Anyone with permission to see an entity can read all annotations on that entity, ...
# Create a new keyword tag session.post(project.links.tags, data={'tags': [{'tag': 'mytag'}]}) # Get the tags for project tags = session.get(project.links.tags) pprint(tags) # Delete a tag session.delete(project.links.tags + "/" + tags[0]._id)
examples/attributes-and-annotations.ipynb
physion/ovation-python
gpl-3.0
Load the data
#code here #train = pd.read_csv
product-buy/notebook/propensity_to_buy.ipynb
amitkaps/full-stack-data-science
mit
3. Refine
# View the first few rows # What are the columns # What are the column types? # How many observations are there? # View summary of the raw data # Check for missing values. If they exist, treat them
product-buy/notebook/propensity_to_buy.ipynb
amitkaps/full-stack-data-science
mit
4. Explore
# Single variate analysis # histogram of target variable # Bi-variate analysis
product-buy/notebook/propensity_to_buy.ipynb
amitkaps/full-stack-data-science
mit
5. Transform
# encode the categorical variables
product-buy/notebook/propensity_to_buy.ipynb
amitkaps/full-stack-data-science
mit
6. Model
# Create train-test dataset # Build decision tree model - depth 2 # Find accuracy of model # Visualize decision tree # Build decision tree model - depth none # find accuracy of model # Build random forest model # Find accuracy model # Bonus: Do cross-validation
product-buy/notebook/propensity_to_buy.ipynb
amitkaps/full-stack-data-science
mit
Create Date And Time Data
# Create dates dates = pd.Series(pd.date_range('2/2/2002', periods=3, freq='M')) # View data dates
machine-learning/encode_days_of_the_week.ipynb
tpin3694/tpin3694.github.io
mit
Show Days Of The Week
# Show days of the week dates.dt.weekday_name
machine-learning/encode_days_of_the_week.ipynb
tpin3694/tpin3694.github.io
mit
Problem 1: Processing Tabular Data from File In this problem, we practice reading csv formatted data and doing some very simple data exploration. Part (a): Reading CSV Data with Numpy Open the file $\mathtt{dataset}$_$\mathtt{HW0.txt}$, containing birth biometrics as well as maternal data for a number of U.S. births, a...
#create a variable for the file dataset_HW0.txt fname = 'dataset_HW0.txt' #fname # Option 1: Open the file and load the data into the numpy array; skip the headers with open(fname) as f: lines = (line for line in f if not line.startswith('#')) data = np.loadtxt(lines, delimiter=',', skiprows=1) # What is t...
Datascience_Lab0.ipynb
scheema/Machine-Learning
mit
Part (b): Simple Data Statistics Compute the mean birth weight and mean femur length for the entire dataset. Now, we want to split the birth data into three groups based on the mother's age: Group I: ages 0-17 Group II: ages 18-34 Group III: ages 35-50 For each maternal age group, compute the mean birth weight and me...
#calculate the overall means birth_weight_mean = data[:,0].mean() birth_weight_mean #calculagte the overall mean for Femur Length femur_length_mean = data[:,1].mean() femur_length_mean # Capture the birth weight birth_weight = data[:,0] #Capture the Femur length femur_length = data[:,1] # Capture the maternal age m...
Datascience_Lab0.ipynb
scheema/Machine-Learning
mit
Part (c): Simple Data Visualization Visualize the data using a 3-D scatter plot (label the axes and title your plot). How does your visual analysis compare with the stats you've computed in Part (b)?
fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for c, m in [('r', 'o')]: ax.scatter(bw_g1, fl_g1, age0_17, edgecolor=c,facecolors=(0,0,0,0), marker=m, s=40) for c, m in [('b', 's')]: ax.scatter(bw_g2, fl_g2, age18_34, edgecolor=c,facecolors=(0,0,0,0), marker=m, s=40) for c, m in [('g', '^')...
Datascience_Lab0.ipynb
scheema/Machine-Learning
mit
Part (d): Simple Data Visualization (Continued) Visualize two data attributes at a time, maternal age against birth weight maternal age against femur length birth weight against femur length using 2-D scatter plots. Compare your visual analysis with your analysis from Part (b) and (c).
plt.scatter(maternal_age,birth_weight, color='r', marker='o') plt.xlabel("maternal age") plt.ylabel("birth weight") plt.show() plt.scatter(maternal_age,femur_length, color='b', marker='s') plt.xlabel("maternal age") plt.ylabel("femur length") plt.show() plt.scatter(birth_weight,femur_length, color='g', marker='^') pl...
Datascience_Lab0.ipynb
scheema/Machine-Learning
mit
Problem 2: Processing Web Data In this problem we practice some basic web-scrapping using Beautiful Soup. Part (a): Opening and Reading Webpages Open and load the page (Kafka's The Metamorphosis) at $\mathtt{http://www.gutenberg.org/files/5200/5200-h/5200-h.htm}$ into a BeautifulSoup object. The object we obtain is a...
# load the file into a beautifulsoup object page = urllib.request.urlopen("http://www.gutenberg.org/files/5200/5200-h/5200-h.htm").read() # prettify the data read from the url and print the first 1000 characters soup = BeautifulSoup(page, "html.parser") print(soup.prettify()[0:1000])
Datascience_Lab0.ipynb
scheema/Machine-Learning
mit
Part (b): Exploring the Parsed HTML Explore the nested data structure you obtain in Part (a) by printing out the following: the content of the head tag the string inside the head tag each child of the head tag the string inside the title tag the string inside the preformatted text (pre) tag the string inside the first...
# print the content of the head tag soup.head # print the string inside the head tag soup.head.title # print each child of the head tag soup.head.meta # print the string inside the title tag soup.head.title.string # print the string inside the pre-formatbted text (pre) tag print(soup.body.pre.string) # print the s...
Datascience_Lab0.ipynb
scheema/Machine-Learning
mit
Part (c): Extracting Text Now we want to extract the text of The Metamorphosis and do some simple analysis. Beautiful Soup provides a way to extract all text from a webpage via the $\mathtt{get}$_$\mathtt{text()}$ function. Print the first and last 1000 characters of the text returned by $\mathtt{get}$_$\mathtt{text()...
print(soup.get_text()[1:1000])
Datascience_Lab0.ipynb
scheema/Machine-Learning
mit
Part (d): Extracting Text (Continued) Using the $\mathtt{find}$_$\mathtt{all()}$ function, extract the text of The Metamorphosis and concatenate the result into a single string. Print out the first 1000 characters of the string as a sanity check.
p = soup.find_all('p') combined_text = '' for node in soup.findAll('p'): combined_text += "".join(node.findAll(text=True)) print(combined_text[0:1000])
Datascience_Lab0.ipynb
scheema/Machine-Learning
mit
Part (e): Word Count Count the number of words in The Metamorphosis. Compute the average word length and plot a histogram of word lengths. You'll need to adjust the number of bins for each histogram. Hint: You'll need to pre-process the text in order to obtain the correct word/sentence length and count.
word_list = combined_text.lower().replace(':','').replace('.','').replace(',', '').replace('"','').replace('!','').replace('?','').replace(';','').split() #print(word_list[0:100]) word_length = [len(n) for n in word_list] print(word_length[0:100]) total_word_length = sum(word_length) print("The total word length: ",...
Datascience_Lab0.ipynb
scheema/Machine-Learning
mit
3. Affine decomposition In order to obtain an affine decomposition, we proceed as in the previous tutorial and recast the problem on a fixed, parameter independent, reference domain $\Omega$. As reference domain which choose the one characterized by $\mu_0 = 1$ which we generate through the generate_mesh notebook provi...
@SCM() @PullBackFormsToReferenceDomain() @ShapeParametrization( ("x[0]", "x[1]"), # subdomain 1 ("mu[0]*(x[0] - 1) + 1", "x[1]"), # subdomain 2 ) class Graetz(EllipticCoerciveProblem): # Default initialization of members @generate_function_space_for_stability_factor def __init__(self, V, **kwargs...
tutorials/04_graetz/tutorial_graetz_2.ipynb
mathLab/RBniCS
lgpl-3.0
4. Main program 4.1. Read the mesh for this problem The mesh was generated by the data/generate_mesh_2.ipynb notebook.
mesh = Mesh("data/graetz_2.xml") subdomains = MeshFunction("size_t", mesh, "data/graetz_physical_region_2.xml") boundaries = MeshFunction("size_t", mesh, "data/graetz_facet_region_2.xml")
tutorials/04_graetz/tutorial_graetz_2.ipynb
mathLab/RBniCS
lgpl-3.0
4.3. Allocate an object of the Graetz class
problem = Graetz(V, subdomains=subdomains, boundaries=boundaries) mu_range = [(0.1, 10.0), (0.01, 10.0), (0.5, 1.5), (0.5, 1.5)] problem.set_mu_range(mu_range)
tutorials/04_graetz/tutorial_graetz_2.ipynb
mathLab/RBniCS
lgpl-3.0
4.4. Prepare reduction with a reduced basis method
reduction_method = ReducedBasis(problem) reduction_method.set_Nmax(30, SCM=50) reduction_method.set_tolerance(1e-5, SCM=1e-3)
tutorials/04_graetz/tutorial_graetz_2.ipynb
mathLab/RBniCS
lgpl-3.0
4.5. Perform the offline phase
lifting_mu = (1.0, 1.0, 1.0, 1.0) problem.set_mu(lifting_mu) reduction_method.initialize_training_set(500, SCM=250) reduced_problem = reduction_method.offline()
tutorials/04_graetz/tutorial_graetz_2.ipynb
mathLab/RBniCS
lgpl-3.0
4.6. Perform an online solve
online_mu = (10.0, 0.01, 1.0, 1.0) reduced_problem.set_mu(online_mu) reduced_solution = reduced_problem.solve() plot(reduced_solution, reduced_problem=reduced_problem)
tutorials/04_graetz/tutorial_graetz_2.ipynb
mathLab/RBniCS
lgpl-3.0
11: Largest product in a grid In the 20×20 grid below, four numbers along a diagonal line have been bolded. \begin{matrix} 08&02&22&97&38&15&00&40&00&75&04&05&07&78&52&12&50&77&91&08\ 49&49&99&40&17&81&18&57&60&87&17&40&98&43&69&48&04&56&62&00\ 81&49&31&73&55&79&14&29&93&71&40&67&53&88&30&03&49&13&36&65\ 52&70&95&23&0...
input_mat = np.array([[ 8, 2,22,97,38,15, 0,40, 0,75, 4, 5, 7,78,52,12,50,77,91, 8], [49,49,99,40,17,81,18,57,60,87,17,40,98,43,69,48, 4,56,62, 0], [81,49,31,73,55,79,14,29,93,71,40,67,53,88,30, 3,49,13,36,65], [52,70,95,23, 4,60,11,42,69,24,68,56, 1,32,56,71,37, 2,36,91], [22,31,16,71,51,67,63,89,41,92,36,54,22,40...
Euler/euler_11-20.ipynb
andrewzwicky/puzzles
mit
12: Highly divisible triangular number The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: ...
for tri in triangle_gen(): if len(factors(tri)) > 500: break tri
Euler/euler_11-20.ipynb
andrewzwicky/puzzles
mit
13: Large sum Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. 37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629 91942213363574161572522430563301811072406154908250 23067588207539...
nums = [37107287533902102798797998220837590246510135740250, 46376937677490009712648124896970078050417018260538, 74324986199524741059474233309513058123726617309629, 91942213363574161572522430563301811072406154908250, 23067588207539346171171980310421047513778063246676, 89261670696623633820136378418383684178734361726757, ...
Euler/euler_11-20.ipynb
andrewzwicky/puzzles
mit
14: Longest Collatz sequence The following iterative sequence is defined for the set of positive integers: $n$ → $n/2$ ($n$ is even) $n$ → $3n + 1$ ($n$ is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (...
collatz_results = {} def collatz_gen(n): yield n while n != 1: if n % 2 == 0: n = n // 2 else: n = 3*n + 1 yield n for i in range(1,1000000): if i not in collatz_results.keys(): temp_dict = {} length = 0 for term in collatz_gen(i): ...
Euler/euler_11-20.ipynb
andrewzwicky/puzzles
mit
15: Lattice paths Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20×20 grid
int(factorial(40) / factorial(20)**2)
Euler/euler_11-20.ipynb
andrewzwicky/puzzles
mit
16: Power digit sum $2^{15}$ = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number $2^{1000}$?
np.sum(list(map(int, str(2**1000))))
Euler/euler_11-20.ipynb
andrewzwicky/puzzles
mit
17: Number letter counts If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. F...
def translate(n): result = '' basic_nums = { 1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine', 10:'ten', 11:'eleven', 12:'twelve', 13:'thirteen', 14:'fourteen'...
Euler/euler_11-20.ipynb
andrewzwicky/puzzles
mit
18: Maximum path sum I By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom of the triangle below: 75 95 64 ...
input_tri = [[75], [95, 64], [17, 47, 82], [18, 35, 87, 10], [20, 4, 82, 47, 65], [19, 1, 23, 75, 3, 34], [88, 2, 77, 73, 7, 63, 67], [99, 65, 4, 28, 6, 16, 70, 92], [41, 41, 26, 56, 83, 40, 80, 70, 33], [41, 48, 72, 33, 47, 32, 37, 16, 94, 29], [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14], [70, 11, 33, 28, 77, ...
Euler/euler_11-20.ipynb
andrewzwicky/puzzles
mit
19: Counting Sundays You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A ...
months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] day = 1 sunday_first_count = 0 for year in range(1900,2001): for month_num, days_in_month in enumerate(months): if month_num == 1: leap = (year % 4 == 0 and not year % 100 == 0) or year % 400 == 0 if leap: da...
Euler/euler_11-20.ipynb
andrewzwicky/puzzles
mit
20: Factorial digit sum n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100!
np.sum(list(map(int, str(factorial(100)))))
Euler/euler_11-20.ipynb
andrewzwicky/puzzles
mit
What did this accomplish? Model can be trained and tested on different data Response values are known for the testing set, and thus predictions can be evaluated Testing accuracy is a better estimate than training accuracy of out-of-sample performance
# STEP 1: split X and y into training and testing sets from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=4) # print the shapes of the new X objects print X_train.shape print X_test.shape # print the shapes of the new y objects p...
Day1/05_model_evaluation_tts.ipynb
dtamayo/MachineLearning
gpl-3.0
Repeat for KNN with K=5:
from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=5) knn.fit(X_train, y_train) y_pred = knn.predict(X_test) print metrics.accuracy_score(y_test, y_pred)
Day1/05_model_evaluation_tts.ipynb
dtamayo/MachineLearning
gpl-3.0
Can you find an even better value for K?
# try K=1 through K=25 and record testing accuracy k_range = range(1, 26) scores = [] # calculate accuracies for each value of K! #Now we plot: import matplotlib.pyplot as plt # allow plots to appear within the notebook %matplotlib inline plt.plot(k_range, scores) plt.xlabel('Value of K for KNN') plt.ylabel('Testing...
Day1/05_model_evaluation_tts.ipynb
dtamayo/MachineLearning
gpl-3.0
Implement an SVM! We've already learned about support vector machines. Now we're going to implement one. We need to find out how to use this thing! We ran some code in the previous notebook that did this for us, but now we need to make things work on our own. Googling for "svm sklearn classifier" gets us to this page. ...
# First we need to import svms from sklearn from sklearn.svm import SVC
30_ML-III/ML_3_Inclass_Homework.ipynb
greenelab/GCB535
bsd-3-clause
The parts inside the parentheses give us the ability to set or change parameters. Anything with an equals sign after it has a default parameter set. In this case, the default C is set to 1.0. There's also a box that gives some description of what each parameter is (only a few of them may make sense to us right now). If...
# Get an SVC with default parameters as our algorithm classifier = SVC() # Fit the classifier to our datasets classifier.fit(X1, y1) # Apply the classifier back to our data and get an accuracy measure train_score = classifier.score(X1, y1) # Print the accuracy print(train_score)
30_ML-III/ML_3_Inclass_Homework.ipynb
greenelab/GCB535
bsd-3-clause
Ouch! Only about 50% accuracy. That's painful! We learned that we could modify C to make the algorithm try to fit the data we show it better. Let's ramp up C and see what happens!
# Get an SVC with a high C classifier = SVC(C = 100) # Fit the classifier to our datasets classifier.fit(X1, y1) # Apply the classifier back to our data and get an accuracy measure train_score = classifier.score(X1, y1) # Print the accuracy print(train_score) import sklearn
30_ML-III/ML_3_Inclass_Homework.ipynb
greenelab/GCB535
bsd-3-clause
Nice! 100% accuracy. This seems like we're on the right track. What we'd really like to do is figure out how we do on held out testing data though. Fortunately, sklearn provides a helper function to make holding out some of the data easy. This function is called train_test_split and we can find its documentation. If we...
# Import the function to split our data: from sklearn.cross_validation import train_test_split # Split things into training and testing - let's have 30% of our data end up as testing X1_train, X1_test, y1_train, y1_test = train_test_split(X1, y1, test_size=.33)
30_ML-III/ML_3_Inclass_Homework.ipynb
greenelab/GCB535
bsd-3-clause
Now let's go ahead and train our classifier on the training data and test it on some held out test data
# Get an SVC again using C = 100 classifier = SVC(C = 100) # Fit the classifier to the training data: classifier.fit(X1_train, y1_train) # Now we're going to apply it to the training labels first: train_score = classifier.score(X1_train, y1_train) # We're also going to applying it to the testing labels: test_score =...
30_ML-III/ML_3_Inclass_Homework.ipynb
greenelab/GCB535
bsd-3-clause
Nice! Now we can see that while our training accuracy is very high, our testing accuracy is much lower. We could say that our model has "overfit" to the data. We learned about overfitting before. You'll get a chance to play with this SVM a bit more below. Before we move to that though, we want to show you how easy it i...
# First, we need to import the classifier from sklearn.tree import DecisionTreeClassifier # Now we're going to get a decision tree classifier with the default parameters classifier = DecisionTreeClassifier() # The 'fit' syntax is the same classifier.fit(X1_train, y1_train) # As is the 'score' syntax train_score = cl...
30_ML-III/ML_3_Inclass_Homework.ipynb
greenelab/GCB535
bsd-3-clause
Oof! That's pretty overfit! We're perfect on the training data but basically flipping a coin on the held out data. A DecisionTreeClassifier has two parameters max_features and max_depth that can really help us prevent overfitting. Let's train a very small tree (no more than 8 features) that's very short (no more than 3...
# Now we're going to get a decision tree classifier with selected parameters classifier = DecisionTreeClassifier(max_features=8, max_depth=3) # The 'fit' syntax is the same classifier.fit(X1_train, y1_train) # As is the 'score' syntax train_score = classifier.score(X1_train, y1_train) test_score = classifier.score(X1...
30_ML-III/ML_3_Inclass_Homework.ipynb
greenelab/GCB535
bsd-3-clause
See the documentation of vcsn.automaton for more details about this function. The syntax used to define the automaton is, however, described here. In order to facilitate the definition of automata, Vcsn provides additional ''magic commands'' to the IPython Notebook. We will see through this guide how use this command....
%%automaton a context = "lal_char(ab), z" $ -> p <2> p -> q <3>a, <4>b q -> q a q -> $
doc/notebooks/Automata.ipynb
pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn
gpl-3.0
The first argument, here a, is the name of the variable in which this automaton is stored:
a
doc/notebooks/Automata.ipynb
pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn
gpl-3.0
You may pass the option -s or --strip to strip the automaton from its layer that keeps the state name you have chosen. In that case, the internal numbers are used, unrelated to the user names (actually, the numbers are assigned to state names as they are encountered starting from 0).
%%automaton --strip a context = "lal_char(ab), z" $ -> p <2> p -> q <3>a, <4>b q -> q a q -> $ a
doc/notebooks/Automata.ipynb
pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn
gpl-3.0
The second argument specifies the format in which the automaton is described, defaulting to auto, which means "guess the format":
%%automaton a dot digraph { vcsn_context = "lal_char(ab), z" I -> p [label = "<2>"] p -> q [label = "<3>a, <4>b"] q -> q [label = a] q -> F } %%automaton a digraph { vcsn_context = "lal_char(ab), z" I -> p [label = "<2>"] p -> q [label = "<3>a, <4>b"] q -> q [label = a] q -> F }
doc/notebooks/Automata.ipynb
pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn
gpl-3.0
Automata entered this way are persistent: they are stored in the notebook and will be recovered when the page is reopened. %automaton: Text-Based Edition of an Automaton In IPython "line magic commands" begin with a single %. The line magic %automaton takes three arguments: 1. the name of the automaton 2. the format y...
%automaton a
doc/notebooks/Automata.ipynb
pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn
gpl-3.0
The real added value is that now you can interactively edit this automaton: changes in the text are immediately propagated on the rendered automaton. When given a fresh variable name, %automaton creates a dummy automaton that you can use as a starting point:
%automaton b fado
doc/notebooks/Automata.ipynb
pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn
gpl-3.0
Beware however that these automata are not persistent: changes will be lost when the notebook is closed. Automata Formats Vcsn supports differents input and output formats. Some, such as tikz, are only export-only formats: they cannot be read by Vcsn. daut (read/write) This simple format is work in progress: its preci...
%%automaton a context = "lal_char(ab), z" $ -> p <2> p -> q <3>a, <4>b q -> q a q -> $
doc/notebooks/Automata.ipynb
pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn
gpl-3.0
dot (read/write) This format relies on the "dot" language of the GraphViz toolkit (http://graphviz.org). This is the default format for I/O in Vcsn. An automaton looks as follows:
%%automaton a dot // The comments are introduced with //, or /* ... */ // // The overall syntax is that of Dot for directed graph ("digraph"). digraph { // The following attribute defines the context of the automaton. vcsn_context = "lal_char, b" // Initial states are denoted by an edge between a node whose name ...
doc/notebooks/Automata.ipynb
pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn
gpl-3.0
efsm (read/write) This format is designed to support import/export with OpenFST (http://openfst.org): it wraps its multi-file format (one file describes the automaton with numbers as transition labels, and one or several others define these labels) into a single format. It is not designed to be used by humans, but rat...
a = vcsn.context('lal_char(ab), zmin').expression('[ab]*a(<2>[ab])').automaton() a efsm = a.format('efsm') print(efsm)
doc/notebooks/Automata.ipynb
pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn
gpl-3.0
The following sequence of operations uses OpenFST to determinize this automaton, and to load it back into Vcsn.
import os # Save the EFSM description of the automaton in a file. with open("a.efsm", "w") as file: print(efsm, file=file) # Compile the EFSM into an OpenFST file. os.system("efstcompile a.efsm >a.fst") # Call OpenFST's determinization. os.system("fstdeterminize a.fst >d.fst") # Convert from OpenFST format to E...
doc/notebooks/Automata.ipynb
pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn
gpl-3.0
For what it's worth, the above sequence of actions is realized by a.fstdeterminize(). Vcsn and OpenFST compute the same automaton.
a.determinize()
doc/notebooks/Automata.ipynb
pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn
gpl-3.0
efsm for transducers (two-tape automata) The following sequence shows the round-trip of a transducer between Vcsn and OpenFST.
t = a.partial_identity() t tefsm = t.format('efsm') print(tefsm) vcsn.automaton(tefsm)
doc/notebooks/Automata.ipynb
pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn
gpl-3.0
Details about the EFSM format The EFSM format is a simple format that puts together the various files that OpenFST uses to serialize and deserialize automata: one or two files to describe the labels (called "symbol tables"), and one to list the transitions. More details about these files can be found on FSM Man Pages....
a = vcsn.B.expression('a+b').standard() a print(a.format('fado'))
doc/notebooks/Automata.ipynb
pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn
gpl-3.0
grail (write) This format is made to exchange automata with the Grail (http://grailplus.org). Weighted automata are not supported.
a = vcsn.B.expression('a+b').standard() a print(a.format('grail'))
doc/notebooks/Automata.ipynb
pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn
gpl-3.0
tikz (write) This format generates a LaTeX document that uses TikZ syntax to draw the automaton. Note that the layout is not computed: all the states are simply reported in a row. You will have to tune the positions of the states by hand. However, it remains a convenient way to start.
a = vcsn.Q.expression('<2>a+<3>b').standard() a print(a.format('tikz'))
doc/notebooks/Automata.ipynb
pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn
gpl-3.0
Mairhuber-Curtis Theorem
# Initializing a R^2 sequencer = ghalton.Halton(2) sequencer.reset() xH=np.array(sequencer.get(9)) print(xH) def show_MC_theorem(s_local=0): i=3 j=4 NC=40 sequencer.reset() xH=np.array(sequencer.get(9)) phi1= lambda s: (s-0.5)*(s-1)/((0-0.5)*(0-1)) phi2= lambda s: (s-0)*(s-1)/((0.5-0)*(0....
SC3/01_MC_theorem_Halton_distance_matrix_and_RBF_interpolation.ipynb
tclaudioe/Scientific-Computing
bsd-3-clause
Halton points vs pseudo-random points in 2D
def plot_random_vs_Halton(n=100): # Number of points to be generated # n=1000 # I am reseting the sequence everytime I generated just to get the same points sequencer.reset() xH=np.array(sequencer.get(n)) np.random.seed(0) xR=np.random.rand(n,2) plt.figure(figsize=(2*M,M)) plt.subp...
SC3/01_MC_theorem_Halton_distance_matrix_and_RBF_interpolation.ipynb
tclaudioe/Scientific-Computing
bsd-3-clause
Interpolation with Distance Matrix from Halton points
def show_R(mH=10): fig= plt.figure(figsize=(2*M*mH/12,M*mH/12)) ax = plt.gca() sequencer.reset() X=np.array(sequencer.get(mH)) R=distance_matrix(X, X) plot_matrices_with_values(ax,R) interact(show_R,mH=(2,20,1))
SC3/01_MC_theorem_Halton_distance_matrix_and_RBF_interpolation.ipynb
tclaudioe/Scientific-Computing
bsd-3-clause
Defining a test function
# The function to be interpolated f=lambda x,y: 16*x*(1-x)*y*(1-y) def showing_f(n=10, elev=40, azim=230): fig = plt.figure(figsize=(2*M,M)) # Creating regular mesh Xr = np.linspace(0, 1, n) Xm, Ym = np.meshgrid(Xr,Xr) Z = f(Xm,Ym) # Wireframe plt.subplot(221,projection='3d') ax = fig...
SC3/01_MC_theorem_Halton_distance_matrix_and_RBF_interpolation.ipynb
tclaudioe/Scientific-Computing
bsd-3-clause
Let's look at $f$
elev_widget = IntSlider(min=0, max=180, step=10, value=40) azim_widget = IntSlider(min=0, max=360, step=10, value=230) interact(showing_f,n=(5,50,5),elev=elev_widget,azim=azim_widget) def eval_interp_distance_matrix(C,X,x,y): R=distance_matrix(X, np.array([[x,y]])) return np.dot(C,R) def showing_f_interpolat...
SC3/01_MC_theorem_Halton_distance_matrix_and_RBF_interpolation.ipynb
tclaudioe/Scientific-Computing
bsd-3-clause
The interpolation with distance matrix itself
interact(showing_f_interpolated,n=(5,50,5),mH=(5,80,5),elev=elev_widget,azim=azim_widget)
SC3/01_MC_theorem_Halton_distance_matrix_and_RBF_interpolation.ipynb
tclaudioe/Scientific-Computing
bsd-3-clause
RBF interpolation
# Some RBF's linear_rbf = lambda r,eps: r gaussian_rbf = lambda r,eps: np.exp(-(eps*r)**2) MQ_rbf = lambda r,eps: np.sqrt(1+(eps*r)**2) IMQ_rbf = lambda r,eps: 1./np.sqrt(1+(eps*r)**2) # The chosen one! But please try all of them! rbf = lambda r,eps: MQ_rbf(r,eps) def eval_interp_rbf(C,X,x,y,eps)...
SC3/01_MC_theorem_Halton_distance_matrix_and_RBF_interpolation.ipynb
tclaudioe/Scientific-Computing
bsd-3-clause
1. Cargamos el conjunto de entrenamiento La manera en la que cargamos el conjunto de entrenamiento podemos observarlo en el Jupyter Notebook 1_Train_Set_Load. 2. Crear vocabulario La manera en la que creamos el voacabulario podemos observarlo en el Jupyter Notebook 2A_Daisy_Features y 2B_Clustering.
path = '../rsc/obj/' mini_kmeans_path = path + 'mini_kmeans.sav' mini_kmeans = pickle.load(open(mini_kmeans_path, 'rb'))
code/notebooks/Prototypes/BoW/Bag_of_Words.ipynb
jasag/Phytoliths-recognition-system
bsd-3-clause
3. Obtención de Bag of Words
trainInstances = [] for imgFeatures in train_features: # extrae pertenencias a cluster pertenencias = mini_kmeans.predict(imgFeatures) # extrae histograma bovw_representation, _ = np.histogram(pertenencias, bins=500, range=(0,499)) # añade al conjunto de entrenamiento final trainInstances.append...
code/notebooks/Prototypes/BoW/Bag_of_Words.ipynb
jasag/Phytoliths-recognition-system
bsd-3-clause
Entrenamiento de un clasificador
from sklearn import svm classifier = svm.SVC(kernel='linear', C=0.01) y_pred = classifier.fit(trainInstances, y_train) import pickle # Módulo para serializar path = '../rsc/obj/' svm_BoW_path = path + 'svm_BoW.sav' pickle.dump(classifier, open(svm_BoW_path, 'wb'))
code/notebooks/Prototypes/BoW/Bag_of_Words.ipynb
jasag/Phytoliths-recognition-system
bsd-3-clause
Functions, loops and branching The following exercises let you practice Python syntax. Do not use any packages not in the standard library except for matplotlib.pyplot which has been imported for you. If you have not done much programming, these exercises will be challenging. Don't give up! For this first exercise, sol...
scores = [ 84, 76, 67, 23, 83, 23, 50, 100, 32, 84, 22, 41, 27, 29, 71, 85, 47, 77, 39, 25, 85, 69, 22, 66, 100, 92, 97, 46, 81, 88, 67, 20, 52, 62, 39, 36, 79, 54, 74, 64, 33, 68, 85, 69, 84, 30, 68, 100, 71, 33, 21, 95, 92, 72, 53, 50, 3...
homework/01_Functions_Loops_Branching_Solutions.ipynb
cliburn/sta-663-2017
mit
2. The Henon map and chaos. (25 points) The Henon map takes a pont $(x_n, y_n)$ in the plane and maps it to $$ x_{n+1} = 1 - a x_n^2 + y_n \ y_{n+1} = b x_n $$ Write a function for the Henon map. It should take the current (x, y) value and return a new pair of coordinates. Set a=1.4 and b=0.3 as defatult arguments. W...
# Your answer here def henon(x, y, a=1.4, b=0.3): """Henon map.""" return (1 - a*x**2 + y, b*x) henon(1, 1) n = 1000 n_store = 50 aa = [i/100 for i in range(100, 141)] xxs = [] for a in aa: xs = [] x, y = 1, 1 for i in range(n - n_store): x, y = henon(x, y, a=a) for i in range(n_stor...
homework/01_Functions_Loops_Branching_Solutions.ipynb
cliburn/sta-663-2017
mit
3. Collatz numbers - Euler project problem 14. (25 points) The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that...
# Your answer here def collatz(n): """Returns Collatz sequence starting with n.""" seq = [n] while n != 1: if n % 2 == 0: n = n // 2 else: n = 3*n + 1 seq.append(n) return seq
homework/01_Functions_Loops_Branching_Solutions.ipynb
cliburn/sta-663-2017
mit
Generator version
def collatz_count(n): """Returns Collatz sequence starting with n.""" count = 1 while n != 1: if n % 2 == 0: n = n // 2 else: n = 3*n + 1 count += 1 return count %%time best_n = 1 best_length = 1 for n in range(2, 1000000): length = len(collatz(n))...
homework/01_Functions_Loops_Branching_Solutions.ipynb
cliburn/sta-663-2017
mit
A simple optimization Ignore starting numbers that have been previously generated since they cannot be longer than the generating sequence.
%%time best_n = 1 best_length = 1 seen = set([]) for n in range(2, 1000000): if n in seen: continue seq = collatz(n) seen.update(seq) length = len(seq) if length > best_length: best_length = length best_n = n print(best_n, best_length)
homework/01_Functions_Loops_Branching_Solutions.ipynb
cliburn/sta-663-2017
mit
4. Reading Ulysses. (30 points) Write a program to download the text of Ulysses (5 points) Open the downloaded file and read the entire sequence into a single string variable called text, discarding the header information (i.e. text should start with \n\n*** START OF THIS PROJECT GUTENBERG EBOOK ULYSSES ***\n\n\n\n\n)...
# Your answer here import urllib.request response = urllib.request.urlopen('http://www.gutenberg.org/files/4300/4300-0.txt') text = response.read().decode()
homework/01_Functions_Loops_Branching_Solutions.ipynb
cliburn/sta-663-2017
mit
```python Alternative version using requests library Although not officially part of the standard libaray, it is so widely used that the standard docs point to it "The Requests package is recommended for a higher-level HTTP client interface." import requests url = 'http://www.gutenberg.org/files/4300/4300-0.txt' text =...
with open('ulysses.txt', 'w') as f: f.write(text) with open('ulysses.txt') as f: text = f.read() start_string = '\n\n*** START OF THIS PROJECT GUTENBERG EBOOK ULYSSES ***\n\n\n\n\n' stop_string = 'End of the Project Gutenberg EBook of Ulysses, by James Joyce' start_idx = text.find(start_string) stop_idx = tex...
homework/01_Functions_Loops_Branching_Solutions.ipynb
cliburn/sta-663-2017
mit
We are looking for the last word found, so search backwards from the end with rfind
idx = text.rfind(best_word,) idx, best_len text[idx:(idx+best_len)]
homework/01_Functions_Loops_Branching_Solutions.ipynb
cliburn/sta-663-2017
mit
Loading the Shapefile This notebook uses the 1:110m Natural Earth countries shapefile. After loading the shapefile, we also fetch the index of the "MAPCOLOR7" field so that we can paint different countries different colors. You can also use your own shapefile - just copy it to the same folder as this notebook, and upda...
import shapefile sf = shapefile.Reader("ne_110m_admin_0_countries/ne_110m_admin_0_countries.shp") mapcolor_idx = [field[0] for field in sf.fields].index("MAPCOLOR7")-1 mapcolor_map = [ "#000000", "#fbb4ae", "#b3cde3", "#ccebc5", "#decbe4", "#fed9a6", "#ffffcc", "#e5d8bd", ]
jupyter-notebooks/vector/shapefile.ipynb
planetlabs/notebooks
apache-2.0
Reprojection The countries shapefile is in the WGS 84 projetion (EPSG:4326). We will reproject to Web Mercator (EPSG:3857) to demonstrate how reprojection. To do this, we construct a Transformer using pyproj. At the same time, set up the rendering bounds. For simplicity, define the bounds in lat/lon and reproject to me...
import pyproj transformer = pyproj.Transformer.from_crs('EPSG:4326', 'EPSG:3857', always_xy=True) BOUNDS = [-180, 180, -75, 80] BOUNDS[0],BOUNDS[2] = transformer.transform(BOUNDS[0],BOUNDS[2]) BOUNDS[1],BOUNDS[3] = transformer.transform(BOUNDS[1],BOUNDS[3])
jupyter-notebooks/vector/shapefile.ipynb
planetlabs/notebooks
apache-2.0
Plotting the Data To display the shapefile, iterate through the shapes in the shapefile. Fetch the mapcolor attribute for each shape and use it to determine the fill color. Collect the points for each shape, and transform them to EPSG:3857 using the transformer constructed above. Plot each shape with pyplot using fill ...
%matplotlib notebook import matplotlib.pyplot as plt for shape in sf.shapeRecords(): for i in range(len(shape.shape.parts)): fillcolor=mapcolor_map[shape.record[mapcolor_idx]] i_start = shape.shape.parts[i] if i==len(shape.shape.parts)-1: i_end = len(shape.shape.points)...
jupyter-notebooks/vector/shapefile.ipynb
planetlabs/notebooks
apache-2.0
Chebyshev differentiation matrix
def cheb(N): if N==0: D=0 x=1 return D,x x = np.cos(np.pi*np.arange(N+1)/N) c=np.hstack((2,np.ones(N-1),2))*((-1.)**np.arange(N+1)) X=np.tile(x,(N+1,1)).T dX=X-X.T D = np.outer(c,1./c)/(dX+np.eye(N+1)) D = D - np.diag(np.sum(D.T,axis=0)) return D,x
SC5/04 Numerical Example of Spectral Differentiation.ipynb
tclaudioe/Scientific-Computing
bsd-3-clause
Understanding how the np.FFT does the FFT
def show_spectral_derivative_example(N): x=np.linspace(2*np.pi/N,2*np.pi,N) u = lambda x: np.sin(x) up = lambda x: np.cos(x) #u = lambda x: np.sin(x)*np.cos(x) #up = lambda x: np.cos(x)*np.cos(x)-np.sin(x)*np.sin(x) v=u(x) K=np.fft.fftfreq(N)*N iK=1j*K vhat=np.fft.fft(v) ...
SC5/04 Numerical Example of Spectral Differentiation.ipynb
tclaudioe/Scientific-Computing
bsd-3-clause
Fractional derivative application
def fractional_derivative(N=10,nu=1): x=np.linspace(2*np.pi/N,2*np.pi,N) u = lambda x: np.sin(x) up = lambda x: np.cos(x) v = u(x) vp=spectralDerivativeByFFT(v,nu) plt.figure(figsize=(10,10)) plt.plot(x,v,'ks-',markersize=12,markeredgewidth=3,label='$\sin(x)$',linewidth=3) plt.plot(x,up(...
SC5/04 Numerical Example of Spectral Differentiation.ipynb
tclaudioe/Scientific-Computing
bsd-3-clause
Example 1: Computing Eigenvalues We are solving: $-u''(x)+x^2\,u(x)=\lambda\, u(x)$ on $\mathbb{R}$
L=8.0 def show_example_1(N=6): h=2*np.pi/N x=np.linspace(h,2*np.pi,N) x=L*(x-np.pi)/np.pi D2=(np.pi/L)**2*my_D2_spec_2pi(N) w, v = np.linalg.eig(-D2+np.diag(x**2)) # eigenvalues = np.sort(np.linalg.eigvals(-D2+np.diag(x**2))) ii = np.argsort(w) w=w[ii] v=v[:,ii] plt.figure(f...
SC5/04 Numerical Example of Spectral Differentiation.ipynb
tclaudioe/Scientific-Computing
bsd-3-clause
Example 2: Solving ODE Solving the following BVP $u_{xx}=\exp(4\,x)$ with $u(-1)=u(1)=0$
def example_2(N=16): D,x = cheb(N) D2 = np.dot(D,D) D2 = D2[1:-1,1:-1] f = np.exp(4*x[1:-1]) u = np.linalg.solve(D2,f) u = np.concatenate(([0],u,[0]),axis=0) plt.figure(figsize=(M,M)) plt.plot(x,u,'k.') xx = np.linspace(-1,1,1000) P = np.polyfit(x, u, N) uu = np....
SC5/04 Numerical Example of Spectral Differentiation.ipynb
tclaudioe/Scientific-Computing
bsd-3-clause
Example 3: Solving ODE Solving the following BVP $u_{xx}=\exp(u)$ with $u(-1)=u(1)=0$
def example_3(N=16,IT=20): D,x = cheb(N) D2 = np.dot(D,D) D2 = D2[1:-1,1:-1] u = np.zeros(N-1) for i in np.arange(IT): u_new = np.linalg.solve(D2,np.exp(u)) change = np.linalg.norm(u_new-u,np.inf) u = u_new u = np.concatenate(([0],u,[0]),axis=0) plt.figure(figs...
SC5/04 Numerical Example of Spectral Differentiation.ipynb
tclaudioe/Scientific-Computing
bsd-3-clause
Example 4: Eigenvalue BVP Solve $u_{xx}=\lambda\,u$ with $u(-1)=u(1)=0$
N_widget = IntSlider(min=2, max=50, step=1, value=10) j_widget = IntSlider(min=1, max=49, step=1, value=5) def update_j_range(*args): j_widget.max = N_widget.value-1 j_widget.observe(update_j_range, 'value') def example_4(N=36,j=5): D,x = cheb(N) D2 = np.dot(D,D) D2 = D2[1:-1,1:-1] lam, V = np....
SC5/04 Numerical Example of Spectral Differentiation.ipynb
tclaudioe/Scientific-Computing
bsd-3-clause
Example 5: (2D) Poisson equation $u_{xx}+u_{yy}=f$ with u=0 on $\partial\Gamma$
elev_widget = IntSlider(min=0, max=180, step=10, value=40) azim_widget = IntSlider(min=0, max=360, step=10, value=230) def example_5(N=10,elev=40,azim=230): D,x = cheb(N) y=x D2 = np.dot(D,D) D2 = D2[1:-1,1:-1] xx,yy=np.meshgrid(x[1:-1],y[1:-1]) xx = xx.flatten() yy = yy.flatten() f...
SC5/04 Numerical Example of Spectral Differentiation.ipynb
tclaudioe/Scientific-Computing
bsd-3-clause
Example 6: (2D) Helmholtz equation $u_{xx}+u_{yy}+k^2\,u=f$ with u=0 on $\partial\Gamma$
elev_widget = IntSlider(min=0, max=180, step=10, value=40) azim_widget = IntSlider(min=0, max=360, step=10, value=230) def example_6(N=10,elev=40,azim=230,k=9,n_contours=8): D,x = cheb(N) y=x D2 = np.dot(D,D) D2 = D2[1:-1,1:-1] xx,yy=np.meshgrid(x[1:-1],y[1:-1]) xx = xx.flatten() yy = yy...
SC5/04 Numerical Example of Spectral Differentiation.ipynb
tclaudioe/Scientific-Computing
bsd-3-clause
Example 7: (2D) $-(u_{xx}+u_{yy})=\lambda\,u$ with u=0 on $\partial\Gamma$
elev_widget = IntSlider(min=0, max=180, step=10, value=40) azim_widget = IntSlider(min=0, max=360, step=10, value=230) N_widget = IntSlider(min=2, max=30, step=1, value=10) j_widget = IntSlider(min=1, max=20, step=1, value=1) def update_j_range(*args): j_widget.max = (N_widget.value-1)**2 j_widget.observe(update_j...
SC5/04 Numerical Example of Spectral Differentiation.ipynb
tclaudioe/Scientific-Computing
bsd-3-clause
A good basic unit of computation for comparing the summation algorithms might be to count the number of assignment statements performed.
def findmin(X): start=time.time() minval= X[0] for ele in X: if minval > ele: minval = ele end=time.time() return minval, end-start def findmin2(X): start=time.time() L = len(X) overallmin = X[0] for i in range(L): minval_i = X[i] for j in range(L...
crack/BigO.ipynb
ernestyalumni/CompPhys
apache-2.0
cf. 2.4. An Anagram Detection Example
def anagramSolution(s1,s2): """ @fn anagramSolution @details 1 string is an anagram of another if the 2nd is simply a rearrangement of the 1st 'heart' and 'earth' are anagrams 'python' and 'typhon' are anagrams """ A = list(s2) # Python strings are immutable, ...
crack/BigO.ipynb
ernestyalumni/CompPhys
apache-2.0
2.4.2. Sort and Compare Solution 2
def anagramSolution2(s1,s2):
crack/BigO.ipynb
ernestyalumni/CompPhys
apache-2.0
For the record, we should mention that there exist many other libraries in Python to parse XML, such as minidom or BeautifulSoup which is an interesting library, when you intend to scrape data from the web. While these might come with more advanced bells and whistles than lxml, they can also be more complex to use, whi...
tree = etree.parse("data/TEI/sonnet18.xml") print(tree)
Chapter 8 - Parsing XML.ipynb
mikekestemont/ghent1516
mit
Now let us start processing the contents of our file. Suppose that we are not really interested in the full hierarchical structure of our file, but just in the rhyme words occuring in it. The high-level function interfind() allows us to easily select all rhyme-element in our tree, regardless of where exactly they occur...
for node in tree.iterfind("//rhyme"): print(node)
Chapter 8 - Parsing XML.ipynb
mikekestemont/ghent1516
mit
Note that the search expression ("//rhyme") has two forward slashes before our actual search term. This is in fact XPath syntax, and the two slashes indicate that the search term can occur anywhere (e.g. not necessarily among a node's direct children). Unfortunately, printing the nodes themselves again isn't really ins...
for node in tree.iterfind("//rhyme"): print(node.tag)
Chapter 8 - Parsing XML.ipynb
mikekestemont/ghent1516
mit
To extract the actual rhyme word contained in the element, we can use the .text property of the nodes:
for node in tree.iterfind("//rhyme"): print(node.text)
Chapter 8 - Parsing XML.ipynb
mikekestemont/ghent1516
mit
OK: under this directory, we appear to have a bunch of XML-files, but their titles are just numbers, which doesn't tell us a lot. Let's have a look at what's the title and author tags in these files:
for filename in os.listdir(dirname): if filename.endswith(".xml"): print("*****") print("\t-", filename) tree = etree.parse(dirname+filename) author_element = tree.find("//author") # find vs iterfind! print("\t-", author_element.text) title_element = tree.find("//titl...
Chapter 8 - Parsing XML.ipynb
mikekestemont/ghent1516
mit