0

In my application I want to be able to display pre defined paragraphs in a multi line textctrl

I assume the text will be saved in a text file and I want to access it by giving a key; for example the text saved under key 101 might be several paragraphs relating to lion, while under key 482 there might be several paragraphs relating to food for sea-lions.

Can anyone suggest a suitable way of holding and retrieving text in this form?

LAK
  • 961
  • 7
  • 18
Psionman
  • 3,084
  • 1
  • 32
  • 65
  • To be more specific, you could store your text paragraphs in a dictionary keyed by the numbers and save it using my pickle-based answer to the question [_How to save an object in Python_](http://stackoverflow.com/questions/4529815/how-to-save-an-object-in-python). – martineau Mar 17 '15 at 15:22

3 Answers3

0

Save the text in a text file, open it using open(), and read the result using read().

For example:

TEXT_DIRECTORY = "/path/to/text"
def text_for_key(key):
    with open(os.path.join(TEXT_DIRECTORY), str(key)) as f:
        return f.read()

Or if you'd prefer one big file rather than many smaller ones, just store it as JSON or some other easy to read format:

import json
with open("/path/to/my/text.json") as f:
   contents = json.load(f)

def text_for_key(key):
    return contents[key]

Then your file would look like:

{101: "Lions...",
 482: "Sea lions...",
...}
Brian Campbell
  • 322,767
  • 57
  • 360
  • 340
  • Thanks Brian. I'll give json a try – Psionman Mar 17 '15 at 15:12
  • I would recommend using pickle (https://docs.python.org/2/library/pickle.html) because it is faster and cooler :). But you need to remember: The pickle module is not intended to be secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source. – KiraLT Mar 17 '15 at 15:15
  • @Lukas Yeah, but it's not easily editable, you need to add separate tools to write out to your file. It's fine if you really need the extra speed, and don't mind not being able to read or write it from other languages, but JSON is available everywhere and human readable and editable. From simplest to most complex, I would rank just plain flat files, JSON, pickle, a real single process database like SQLite, and then a real multi-user database like PostgreSQL. For the described use case, I would recommend staying on the simpler end of that spectrum, but all of the choices have their merits. – Brian Campbell Mar 17 '15 at 15:25
0

I would recommend using pickle. It is faster than json and cooler way to save something to file.

Warning The pickle module is not intended to be secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source.

import pickle
import os

class Database(object):

    def __init__(self, name='default'):
        self.name = '{}.data'.format(name)
        self.data = None
        self.read()

    def save(self):
        with open(self.name, 'wb') as f:
            self.data = pickle.dump(self.data, f)

    def read(self):
        if os.path.isfile(self.name):
            with open(self.name, 'rb') as f:
                self.data = pickle.load(f)
        else:
            self.data = {}

    def set(self, key, value):
        self.data[key] = value

    def get(self, key):
        return self.data[key]

Usage:

database = Database('db1')
database.set(482, 'Sea lions...')
print(database.get(482))
database.save()
KiraLT
  • 2,385
  • 1
  • 24
  • 36
0

Look at using sqlite3, I believe that it is perfect for what you require, without the hassle of going down the full blown database route. Here is an example from the command line of creating a database, populating it with a key and some text then printing out the contents. Coding in python for sqlite3 is straightforward and well documented.

$ sqlite3 text.db
SQLite version 3.8.2 2013-12-06 14:53:30
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> CREATE TABLE "txt" ("txt_id" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE  DEFAULT 1, "the_text" TEXT);

sqlite> insert into txt ("txt_id","the_text") values (1,"a great chunk of text");

sqlite> insert into txt ("txt_id","the_text") values (2,"Elephants are large mammals of the family Elephantidae and the order Proboscidea. Two species are traditionally recognised, the African elephant (Loxodonta africana) and the Asian elephant (Elephas maximus), although some evidence suggests that African bush elephants and African forest elephants are separate species (L. africana and L. cyclotis respectively). Elephants are scattered throughout sub-Saharan Africa, South Asia, and Southeast Asia. Elephantidae are the only surviving family of the order Proboscidea; other, now extinct, families of the order include mammoths and mastodons. Male African elephants are the largest surviving terrestrial animals and can reach a height of 4 m (13 ft) and weigh 7,000 kg (15,000 lb). All elephants have several distinctive features the most notable of which is a long trunk or proboscis, used for many purposes, particularly breathing, lifting water and grasping objects. Their incisors grow into tusks, which can serve as weapons and as tools for moving objects and digging. Elephants' large ear flaps help to control their body temperature. Their pillar-like legs can carry their great weight. African elephants have larger ears and concave backs while Asian elephants have smaller ears and convex or level backs.");

sqlite> select * from txt;

1|a great chunk of text

2|Elephants are large mammals of the family Elephantidae and the order Proboscidea. Two species are traditionally recognised, the African elephant (Loxodonta africana) and the Asian elephant (Elephas maximus), although some evidence suggests that African bush elephants and African forest elephants are separate species (L. africana and L. cyclotis respectively). Elephants are scattered throughout sub-Saharan Africa, South Asia, and Southeast Asia. Elephantidae are the only surviving family of the order Proboscidea; other, now extinct, families of the order include mammoths and mastodons. Male African elephants are the largest surviving terrestrial animals and can reach a height of 4 m (13 ft) and weigh 7,000 kg (15,000 lb). All elephants have several distinctive features the most notable of which is a long trunk or proboscis, used for many purposes, particularly breathing, lifting water and grasping objects. Their incisors grow into tusks, which can serve as weapons and as tools for moving objects and digging. Elephants' large ear flaps help to control their body temperature. Their pillar-like legs can carry their great weight. African elephants have larger ears and concave backs while Asian elephants have smaller ears and convex or level backs.

sqlite> 
Brian Campbell
  • 322,767
  • 57
  • 360
  • 340
Rolf of Saxony
  • 21,661
  • 5
  • 39
  • 60