Newer
Older
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Text input/output\n",
"\n",
"In this section we will explore how to write and/or retrieve our data from text files.\n",
"\n",
"Most of the functionality for reading/writing files and manipulating strings is available without any imports. However, you can find some additional functionality in the [`string`](https://docs.python.org/3.6/library/string.html) module.\n",
"\n",
"Most of the string functions are available as methods on string objects. This means that you can use the ipython autocomplete to check for them."
]
},
{
"cell_type": "code",
"outputs": [],
"source": [
"empty_string = ''"
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"empty_string. # after running the code block above, put your cursor behind the dot and press tab to get a list of methods"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* [Reading/writing files](#reading-writing-files)\n",
"* [Creating new strings](#creating-new-strings)\n",
" * [String syntax](#string-syntax)\n",
" * [Unicode versus bytes](#unicode-versus-bytes)\n",
" * [Converting objects into strings](#converting-objects-into-strings)\n",
" * [Combining strings](#combining-strings)\n",
" * [String formattings](#string-formatting)\n",
"* [Extracting information from strings](#extracting-information-from-strings)\n",
" * [Splitting strings](#splitting-strings)\n",
" * [Converting strings to numbers](#converting-strings-to-numbers)\n",
" * [Regular expressions](#regular-expressions)\n",
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"* [Exercises](#exercises)\n",
"\n",
"<a class=\"anchor\" id=\"reading-writing-files\"></a>\n",
"## Reading/writing files\n",
"The syntax to open a file in python is `with open(<filename>, <mode>) as <file_object>: <block of code>`, where\n",
"* `filename` is a string with the name of the file\n",
"* `mode` is one of 'r' (for read-only access), 'w' (for writing a file, this wipes out any existing content), 'a' (for appending to an existing file).\n",
"* `file_object` is a variable name which will be used within the `block of code` to access the opened file.\n",
"\n",
"For example the following will read all the text in `README.md` and print it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"with open('README.md', 'r') as readme_file:\n",
" print(readme_file.read())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"> The `with` statement is an advanced python feature, however you will probably only encounter it when opening files. In that context it merely ensures that the file will be properly closed as soon as the program leaves the `with` statement (even if an error is raised within the `with` statement).\n",
"\n",
"You could also use the `readlines()` method to get a list of all the lines.\n",
"\n",
"A very similar syntax is used to write files:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"with open('02_text_io/my_file', 'w') as my_file:\n",
" my_file.write('This is my first line\\n')\n",
" my_file.writelines(['Second line\\n', 'and the third\\n'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that no new line characters get added automatically. We can investigate the resulting file using"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"> Any lines starting with `!` will be interpreted as shell commands by ipython. It is great when playing around in the ipython notebook or in the ipython terminal, however it is an ipython-only feature and hence is not available when writing python scripts. How to call shell commands from python will be discussed in the `scripts` practical.\n",
"\n",
"If we want to add to the existing file we can open it in the append mode:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"with open('02_text_io/my_file', 'a') as my_file:\n",
" my_file.write('More lines is always better\\n')\n",
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Below we will discuss how we can convert python objects to strings to store in these files and how to extract those python objects from strings again.\n",
"\n",
"<a class=\"anchor\" id=\"creating-new-strings\"></a>\n",
"## Creating new strings\n",
"\n",
"<a class=\"anchor\" id=\"string-syntax\"></a>\n",
"### String syntax\n",
"Single-line strings can be created in python using either single or double quotes"
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"a_string = 'To be or not to be'\n",
"same_string = \"To be or not to be\"\n",
"print(a_string == same_string)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The main rationale for choosing between single or double quotes, is whether the string itself will contain any quotes. You can include a single quote in a string surrounded by single quotes by escaping it with the `\\` character, however in such a case it would be more convenient to use double quotes:"
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"a_string = \"That's the question\"\n",
"same_string = 'That\\'s the question'\n",
"print(a_string == same_string)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"New-lines (`\\n`), tabs (`\\t`) and many other special characters are supported"
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"a_string = \"This is the first line.\\nAnd here is the second.\\n\\tThe third starts with a tab.\"\n",
"print(a_string)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"However, the easiest way to create multi-line strings is to use a triple quote (again single or double quotes can be used). Triple quotes allow your string to span multiple lines:"
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"multi_line_string = \"\"\"This is the first line.\n",
"And here is the second.\n",
"\\tThird line starts with a tab.\"\"\"\n",
"print(multi_line_string)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you don't want python to reintepret your `\\n`, `\\t`, etc. in your strings, you can prepend the quotes enclosing the string with an `r`. This will lead to python interpreting the following string as raw text."
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"single_line_string = r\"This string is not multiline.\\nEven though it contains the \\n character\"\n",
"print(single_line_string)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"One pitfall when creating a list of strings is that python automatically concatenates string literals, which are only separated by white space:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"my_list_of_strings = ['a', 'b', 'c' 'd', 'e']\n",
"print(\"The 'c' and 'd' got concatenated, because we forgot the comma:\", my_list_of_strings)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"unicode-versus-bytes\"></a>\n",
"#### unicode versus bytes\n",
"To encourage the spread of python around the world, python 3 switched to using unicode as the default for strings and code (which is one of the main reasons for the incompatibility between python 2 and 3).\n",
"This means that each element in a string is a unicode character (using [UTF-8 encoding](https://docs.python.org/3/howto/unicode.html)), which can consist of one or more bytes.\n",
"The advantage is that any unicode characters can now be used in strings or in the code itself:"
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"Δ = \"café\"\n",
"print(Δ)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In python 2 each element in a string was a single byte rather than a potentially multi-byte character. You can convert back to interpreting your sequence as a unicode string or a byte array using:\n",
"* `encode()` called on a string converts it into a bytes array (`bytes` object)\n",
"* `decode()` called on a `bytes` array converts it into a unicode string."
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"delta = \"Δ\"\n",
"print('The character', delta, 'consists of the following 2 bytes', delta.encode())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"These byte arrays can be created directly be prepending the quotes enclosing the string with a `b`, which tells python 3 to interpret the following as a byte array:"
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"a_byte_array = b'\\xce\\xa9'\n",
"print('The two bytes ', a_byte_array, ' become single unicode character (', a_byte_array.decode(), ') with UTF-8 encoding')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Especially in code dealing with strings (e.g., reading/writing of files) many of the errors arising of running python 2 code in python 3 arise from the mixing of unicode strings with byte arrays. Decoding and/or encoding some of these objects can often fix these issues.\n",
"\n",
"By default any file opened in python will be interpreted as unicode. If you want to treat a file as raw bytes, you have to include a 'b' in the `mode` when calling the `open()` function:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os.path as op\n",
"with open(op.expandvars('${FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz'), 'rb') as gzipped_nifti:\n",
" print('First few bytes of gzipped NIFTI file:', gzipped_nifti.read(10))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"> We use the `expandvars()` function here to insert the FSLDIR environmental variable into our string. This function will be presented in the file management practical.\n",
"\n",
"<a class=\"anchor\" id=\"converting-objects-into-strings\"></a>\n",
"### converting objects into strings\n",
"There are two functions to convert python objects into strings, `repr()` and `str()`.\n",
"All other functions that rely on string-representations of python objects will use one of these two (for example the `print()` function will call `str()` on the object).\n",
"\n",
"The goal of the `str()` function is to be readable, while the goal of `repr()` is to be unambiguous. Compare"
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"print(str(\"3\"))\n",
"print(str(3))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"print(repr(\"3\"))\n",
"print(repr(3))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In both cases you get the value of the object (3), but only the `repr` returns enough information to actually know the type of the object.\n",
"Perhaps the difference is clearer with a more advanced object.\n",
"The `datetime` module contains various classes and functions to work with dates (there is also a `time` module).\n",
"Here we will look at the alternative string representations of the `datetime` object itself:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from datetime import datetime\n",
"print('str(): ', str(datetime.now()))\n",
"print('repr(): ', repr(datetime.now()))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that the result from `str()` is human-readable as a date, while the result from `repr()` is more useful if you wanted to recreate the `datetime` object.\n",
"\n",
"<a class=\"anchor\" id=\"combining-strings\"></a>\n",
"### Combining strings\n",
"The simplest way to concatenate strings is to simply add them together:"
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"a_string = \"Part 1\"\n",
"other_string = \"Part 2\"\n",
"full_string = a_string + \", \" + other_string\n",
"print(full_string)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Given a whole sequence of strings, you can concatenate them together using the `join()` method:"
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"list_of_strings = ['first', 'second', 'third', 'fourth']\n",
"full_string = ', '.join(list_of_strings)\n",
"print(full_string)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that the string on which the `join()` method is called (`', '` in this case) is used as a delimiter to separate the different strings. If you just want to concatenate the strings you can call `join()` on the empty string:"
]
},
{
"cell_type": "code",
"execution_count": null,
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
"outputs": [],
"source": [
"list_of_strings = ['first', 'second', 'third', 'fourth']\n",
"full_string = ''.join(list_of_strings)\n",
"print(full_string)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"string-formatting\"></a>\n",
"### String formatting\n",
"Using the techniques in [Combining strings](#combining-strings) we can build simple strings. For longer strings it is often useful to first write a template strings with some placeholders, where variables are later inserted. Built into python are currently 4 different ways of doing this (with many packages providing similar capabilities):\n",
"* the recommended [new-style formatting](https://docs.python.org/3.6/library/string.html#format-string-syntax).\n",
"* printf-like [old-style formatting](https://docs.python.org/3/library/stdtypes.html#old-string-formatting)\n",
"* [formatted string literals](https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings) (these are only available in python 3.6+)\n",
"* bash-like [template-strings](https://docs.python.org/3.6/library/string.html#template-strings)\n",
"\n",
"Here we provide a single example using the first three methods, so you can recognize them in the future.\n",
"\n",
"First the old print-f style. Note that this style is invoked by using the modulo (`%`) operator on the string. Every placeholder (starting with the `%`) is then replaced by one of the values provided."
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"a = 3\n",
"b = 1 / 3\n",
"\n",
"print('%.3f = %i + %.3f' % (a + b, a, b))\n",
"print('%(total).3f = %(a)i + %(b).3f' % {'a': a, 'b': b, 'total': a + b})"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Then the recommended new style formatting (You can find a nice tutorial [here](https://www.digitalocean.com/community/tutorials/how-to-use-string-formatters-in-python-3)). Note that this style is invoked by calling the `format()` method on the string and the placeholders are marked by the curly braces `{}`."
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"a = 3\n",
"b = 1 / 3\n",
"\n",
"print('{:.3f} = {} + {:.3f}'.format(a + b, a, b))\n",
"print('{total:.3f} = {a} + {b:.3f}'.format(a=a, b=b, total=a+b))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that the variable `:` delimiter separates the variable identifiers on the left from the formatting rules on the right.\n",
"Finally the new, fancy formatted string literals (only available in python 3.6+).\n",
"This new format is very similar to the recommended style, except that all placeholders are automatically evaluated in the local environment at the time the template is defined.\n",
"This means that we do not have to explicitly provide the parameters (and we can evaluate the sum inside the string!), although it does mean we also can not re-use the template."
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"a = 3\n",
"b = 1/3\n",
"\n",
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This code block will fail in fslpython, since it uses python 3.5.\n",
"\n",
"\n",
"<a class=\"anchor\" id=\"extracting-information-from-strings\"></a>\n",
"## Extracting information from strings\n",
"<a class=\"anchor\" id=\"splitting-strings\"></a>\n",
"### Splitting strings\n",
"The simplest way to extract a sub-string is to use slicing"
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"a_string = 'abcdefghijklmnopqrstuvwxyz'\n",
"print(a_string[10]) # create a string containing only the 11th character\n",
"print(a_string[20:]) # create a string containing the 21st character onward\n",
"print(a_string[::-1]) # creating the reverse string"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you are not sure, where to cut into a string, you can use the `find()` method to find the first occurrence of a sub-string or `findall()` to find all occurrences."
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"a_string = 'abcdefghijklmnopqrstuvwxyz'\n",
"index = a_string.find('fgh')\n",
"print(a_string[:index]) # extracts the sub-string up to the first occurence of 'fgh'\n",
"print('index for non-existent sub-string', a_string.find('cats')) # note that find returns -1 when it can not find the sub-string rather than raising an error."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can automate this process of splitting a string at a sub-string using the `split()` method. By default it will split a string at the white space."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print('The split() method\\trecognizes a wide variety\\nof white space'.split())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To separate a comma separated list we will need to supply the delimiter to the `split()` method. We can then use the `strip()` method to remove any whitespace at the beginning or end of the string:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"scientific_packages_string = \"numpy, scipy, pandas, matplotlib, nibabel\"\n",
"list_with_whitespace = scientific_packages_string.split(',')\n",
"list_without_whitespace = [individual_string.strip() for individual_string in list_with_whitespace]\n",
"print(list_without_whitespace)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"> We use the syntax `[<expr> for <element> in <sequence>]` here which applies the `expr` to each `element` in the `sequence` and returns the resulting list. This is a list comprehension - a convenient form in python to create a new list from the old one.\n",
"\n",
"<a class=\"anchor\" id=\"converting-strings-to-numbers\"></a>\n",
"### Converting strings to numbers\n",
"Once you have extracted a number from a string, you can convert it into an actual integer or float by calling respectively `int()` or `float()` on it. `float()` understands a wide variety of different ways to write numbers:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(int(\"3\"))\n",
"print(float(\"3\"))\n",
"print(float(\"3.213\"))\n",
"print(float(\"3.213e5\"))\n",
"print(float(\"3.213E-25\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"regular-expressions\"></a>\n",
"### Regular expressions\n",
"Regular expressions are used for looking for specific patterns in a longer string. This can be used to extract specific information from a well-formatted string or to modify a string. In python regular expressions are available in the [re](https://docs.python.org/3/library/re.html#re-syntax) module.\n",
"\n",
"A full discussion of regular expression goes far beyond this practical. If you are interested, have a look [here](https://docs.python.org/3/howto/regex.html).\n",
"## Exercises\n",
"### Joining/splitting strings\n",
"The file 02_text_io/input.txt contains integers in a 2-column format (separated by spaces). Read in this file and write it back out in 2-rows separated by comma's."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"input_filename = '02_text_io/input.txt'\n",
"out_filename = '02_text_io/output.txt'\n",
"\n",
"with open(input_filename, 'r') as input_file:\n",
" ...\n",
"\n",
"with open(output_filename, 'w') as output_file:\n",
" ..."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### String formatting and regular expressions\n",
"Given a template for MRI files:\n",
"`s<subject_id>/<modality>_<res>mm.nii.gz`\n",
"where `<subject_id>` is a 6-digit subject-id, `<modality>` is one of T1w, T2w, or PD, and `<res>` is the resolution of the image (up to one digits behind the dot, e.g. 1.5)\n",
"Write a function that takes the subject_id (as an integer), the modality (as a string), and the resolution (as a float) and returns the complete filename (Hint: use one of the formatting techniques mentioned in [String formatting](#string-formatting))."
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"def get_filename(subject_id, modality, resolution):\n",
" ..."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For a more difficult exercise, write a function that extracts the subject id, modality, and resolution from a filename name (using a regular expression or by using `find` and `split` to access relevant parts of the string)"
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"def get_parameters(filename):\n",
" ...\n",
" return subject_id, modality, resolution"
]
}
],
"nbformat": 4,
"nbformat_minor": 2
}