| 1 |
""" |
| 2 |
Example of how to use the :py:class:`~pymzml.utils.GSGW.GSGW` class to create |
| 3 |
igzip file to load and create a copy of "Moby Dick" with every chapter indexed |
| 4 |
with its number. |
| 5 |
The file created can be read by :py:module:`~pymzml.utils.read_moby_dick` |
| 6 |
""" |
| 7 |
|
| 8 |
|
| 9 |
n |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
import urllib.request |
| 31 |
import re |
| 32 |
from GSGW import GSGW |
| 33 |
import pymzml.regex_patterns as regex_patterns |
| 34 |
|
| 35 |
moby_dick_url = ( |
| 36 |
"http://faculty.washington.edu/stepp/courses/" |
| 37 |
"2004autumn/tcss143/lectures/files/2004-11-08/mobydick.txt" |
| 38 |
) |
| 39 |
|
| 40 |
response = urllib.request.urlopen(moby_dick_url) |
| 41 |
moby_dick_txt = response.read().decode("utf-8").split("\n") |
| 42 |
|
| 43 |
|
| 44 |
def index_by_chapter(txt): |
| 45 |
""" |
| 46 |
Iterate the text file while collecting the data for each chapter and compressing it |
| 47 |
|
| 48 |
Args: |
| 49 |
txt(str): Moby Dick text as string |
| 50 |
""" |
| 51 |
chapter_start = regex_patterns.MOBY_DICK_CHAPTER_PATTERN |
| 52 |
general_seekable_gzip_writer = GSGW( |
| 53 |
file="Moby_Dick_indexed.gz", |
| 54 |
max_idx=42, |
| 55 |
max_idx_len=9, |
| 56 |
max_offset_len=6, |
| 57 |
output_path="./Moby_Dick_indexed.gz", |
| 58 |
) |
| 59 |
|
| 60 |
with general_seekable_gzip_writer as index_writer: |
| 61 |
current_chapter = "" |
| 62 |
for line in txt: |
| 63 |
if re.match(chapter_start, line): |
| 64 |
match = re.match(chapter_start, line) |
| 65 |
current_chapter_number = int(match.group(1)) - 1 |
| 66 |
print("indexing chapter {0}".format(current_chapter_number), end="\r") |
| 67 |
index = "Chapter{0}".format(current_chapter_number) |
| 68 |
index_writer.add_data(current_chapter, index) |
| 69 |
current_chapter = "" |
| 70 |
else: |
| 71 |
current_chapter += line |
| 72 |
current_chapter_number += 1 |
| 73 |
|
| 74 |
index = "Chapter{0}".format(current_chapter_number) |
| 75 |
index_writer.add_data(current_chapter, index) |
| 76 |
print("index chapter {0} ".format(index), end="\r") |
| 77 |
index_writer.write_index() |
| 78 |
print("Indexed {0} chapters".format(current_chapter_number)) |
| 79 |
|
| 80 |
|
| 81 |
if __name__ == "__main__": |
| 82 |
index_by_chapter(moby_dick_txt) |