### Run Tests with Tox Source: https://github.com/izimobil/polib/blob/master/docs/contributing.md Use tox to run tests, which handles environment setup. Install tox first if you haven't already. ```shell $ cd /path/to/polib/ $ pip install tox $ tox ``` -------------------------------- ### Install polib using easy_install Source: https://github.com/izimobil/polib/blob/master/docs/installation.md Use this command to install polib via the easy_install package manager. Ensure easy_install is installed. ```bash easy_install polib ``` -------------------------------- ### Install Polib using pip Source: https://github.com/izimobil/polib/blob/master/README.rst Use pip to install the polib library. This is the standard method for installing Python packages. ```bash $ pip install polib ``` -------------------------------- ### Install polib from a downloaded package Source: https://github.com/izimobil/polib/blob/master/docs/installation.md Run this command from the unpacked polib directory to install the library manually. You may need administrative privileges. ```bash python setup.py install ``` -------------------------------- ### Example Usage of __unicode__ Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/BaseEntry.md Demonstrates how to use the __unicode__ method to get the PO file format representation of a POEntry object. The output shows the formatted msgid and msgstr. ```python entry = polib.POEntry(msgid='Hello', msgstr='Bonjour') print(entry.__unicode__()) ``` -------------------------------- ### Example Gettext Catalog Entry Source: https://github.com/izimobil/polib/blob/master/docs/quickstart.md A simple example of a gettext catalog entry, showing the original string and its translation. ```gettext #: lib/error.c:116 msgid "Unknown system error" msgstr "Error desconegut del sistema" ``` -------------------------------- ### Create Simple POEntry Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/POEntry.md Example of creating a simple POEntry with a message ID, translation, comment, and occurrence information. Ensure polib is imported. ```python import polib # Simple entry entry = polib.POEntry( msgid='Hello, World!', msgstr='Bonjour, Monde!', comment='Greeting message', occurrences=[('main.py', 42)] ) ``` -------------------------------- ### Clone polib repository using Git Source: https://github.com/izimobil/polib/blob/master/docs/installation.md Use this command to clone the latest development code from the polib Git repository. This requires Git to be installed. ```bash git clone https://github.com/izimobil/polib/ ``` -------------------------------- ### List Behavior Examples Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/BaseFile.md Demonstrates standard list operations available on BaseFile objects due to inheritance from the list type. This includes indexing, slicing, iteration, length checking, removal, and sorting of entries. ```python po = polib.POFile() # Indexing first = po[0] last = po[-1] # Slicing subset = po[10:20] # Iteration for entry in po: print(entry) # Length count = len(po) # Removing po.pop(0) po.remove(entry) del po[0] # Sorting po.sort() ``` -------------------------------- ### Checking Length and Membership in POFile Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/POFile.md Shows how to get the total number of entries in a POFile object and check if a specific entry exists within it. Membership testing compares 'msgid' and 'msgctxt'. ```python # Length total_entries = len(po) # Membership test (checks msgid and msgctxt equality) if entry in po: print("Entry already exists") ``` -------------------------------- ### Create and Save MOFile Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/MOFile.md Demonstrates how to create an empty MOFile, add entries, set encoding, and save it to a binary .mo file. ```python import polib # Create empty MO file mo = polib.MOFile() mo.encoding = 'utf-8' # Add entries entry = polib.MOEntry( msgid='Hello', msgstr='Bonjour' ) mo.append(entry) # Save as binary mo.save('translations.mo') ``` -------------------------------- ### Create and Populate POFile Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/POFile.md Demonstrates how to create an empty POFile, set metadata, add new entries with translations and occurrences, and save the file. ```python import polib # Create empty PO file po = polib.POFile() po.metadata = { 'Project-Id-Version': '1.0', 'Content-Type': 'text/plain; charset=UTF-8', } # Add entries entry = polib.POEntry( msgid='Hello', msgstr='Bonjour', occurrences=[('main.py', 10)] ) po.append(entry) # Save to file po.save('translations.po') ``` -------------------------------- ### Configure POFile Instance at Creation and After Source: https://github.com/izimobil/polib/blob/master/_autodocs/configuration.md Initialize a POFile with specific configuration options like wrapwidth, encoding, and check_for_duplicates. These attributes can also be modified after the instance is created. ```python po = polib.POFile( wrapwidth=78, encoding='utf-8', check_for_duplicates=False ) # Modify after creation po.wrapwidth = 100 po.encoding = 'iso-8859-1' po.fpath = '/path/to/file.po' po.check_for_duplicates = True ``` -------------------------------- ### Get Unicode String Representation Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/BaseFile.md Use the __unicode__ method to get the text representation of the file contents formatted as a PO file. This is useful for outputting or saving the PO data. ```python po = polib.POFile() output = po.__unicode__() print(output) ``` -------------------------------- ### Creating an MOEntry Object Source: https://github.com/izimobil/polib/blob/master/_autodocs/ARCHITECTURE.md Shows how an MOEntry object can be created, demonstrating the Adapter pattern. Note that 'comment' and 'flags' are accepted but ignored. ```python entry = polib.MOEntry() entry.comment = 'ignored' # Accepted but ignored entry.flags = [] # Accepted but ignored ``` -------------------------------- ### __str__ Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/MOEntry.md Get the string representation of the MOEntry object. ```APIDOC ## __str__ ### Description Get string representation. ### Signature ```python def __str__(self) -> str ``` ``` -------------------------------- ### Create a new PO file with metadata Source: https://github.com/izimobil/polib/blob/master/docs/quickstart.md Initialize an empty POFile object and set its metadata. This is useful for creating new translation catalogs from scratch. ```python import polib po = polib.POFile() po.metadata = { 'Project-Id-Version': '1.0', 'Report-Msgid-Bugs-To': 'you@example.com', 'POT-Creation-Date': '2007-10-18 14:00+0100', 'PO-Revision-Date': '2007-10-18 14:00+0100', 'Last-Translator': 'you ', 'Language-Team': 'English ', 'MIME-Version': '1.0', 'Content-Type': 'text/plain; charset=utf-8', 'Content-Transfer-Encoding': '8bit', } ``` -------------------------------- ### POEntry.fuzzy (property) Source: https://github.com/izimobil/polib/blob/master/_autodocs/INDEX.md Gets or sets the fuzzy flag for a PO entry. ```APIDOC ## POEntry.fuzzy (property) ### Description Gets or sets the fuzzy flag for a PO entry. ### Purpose Get/set fuzzy flag ``` -------------------------------- ### Get String Representation (__str__) Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/MOEntry.md Returns the string representation of the entry. ```python def __str__(self) -> str: ``` -------------------------------- ### Initialize _BaseFile Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/BaseFile.md The constructor for _BaseFile accepts various parameters to configure file path, line wrapping, encoding, and duplicate checking. It initializes attributes like fpath, wrapwidth, encoding, check_for_duplicates, header, metadata, and metadata_is_fuzzy. ```python class _BaseFile(list) ``` -------------------------------- ### String Representation Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/POEntry.md Provides methods to get the string representation of a POEntry object in the standard PO file format. ```APIDOC ## String Representation This section describes how to obtain the string representation of a `POEntry` object, which conforms to the standard PO file format. ### Methods - `__unicode__(self, wrapwidth=78) -> str`: Returns the PO file format representation of the entry, with an optional wrap width. - `__str__(self) -> str`: Returns the string representation of the entry. ### Example ```python entry = polib.POEntry( msgid='Hello', msgstr='Bonjour', comment='Greeting', occurrences=[('file.py', 10)] ) print(entry) # Output: # # Greeting # #: file.py:10 # msgid "Hello" # msgstr "Bonjour" ``` ``` -------------------------------- ### Work with Compiled MO Files (Python) Source: https://github.com/izimobil/polib/blob/master/_autodocs/README.md Convert a .po file to a .mo file, load the .mo file, and iterate through its entries. Also demonstrates converting back to .po. ```python import polib # Create from PO po = polib.pofile('translations.po') po.save_as_mofile('translations.mo') # Load compiled file mo = polib.mofile('translations.mo') for entry in mo: print(f"{entry.msgid} → {entry.msgstr}") # Convert back to editable PO mo.save_as_pofile('translations_out.po') ``` -------------------------------- ### Building a PO File Incrementally Source: https://github.com/izimobil/polib/blob/master/_autodocs/ARCHITECTURE.md Demonstrates the Builder pattern for creating and saving PO files. Use this to construct PO files programmatically. ```python po = polib.POFile() po.metadata = {...} po.append(entry1) po.append(entry2) ... po.save('file.po') ``` -------------------------------- ### Get Untranslated Entries Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/POFile.md Retrieves and iterates over all entries in a PO file that are missing a translation. Obsolete and fuzzy entries are excluded. ```python po = polib.pofile('translations.po') for entry in po.untranslated_entries(): print(f"Missing translation for: {entry.msgid}") ``` -------------------------------- ### Polib File Loading Pipeline Source: https://github.com/izimobil/polib/blob/master/_autodocs/ARCHITECTURE.md Illustrates the step-by-step process of loading a file, including path validation, encoding detection, parser selection, and state machine-based parsing. ```text User Input (file path or string) ↓ _is_file() checks if it's a path ↓ Encoding Detection (detect_encoding) ├─ Reads Content-Type header for charset ├─ Falls back to default_encoding if not found └─ Validates encoding is available ↓ Parser Selection ├─ PO format → _POFileParser └─ MO format → _MOFileParser ↓ Parser (FSM-based) ├─ Reads file line-by-line (or from string) ├─ State machine tracks current field (msgid, msgstr, etc.) ├─ Accumulates entry data ├─ On entry completion, creates POEntry or MOEntry └─ Returns file instance with entries ↓ Result: POFile or MOFile instance ``` -------------------------------- ### Get Translated Entries Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/POFile.md Retrieves and iterates over all entries in a PO file that have a valid translation. Obsolete and fuzzy entries are excluded. ```python po = polib.pofile('translations.po') for entry in po.translated_entries(): print(f"{entry.msgid} -> {entry.msgstr}") ``` -------------------------------- ### Get translation percentage Source: https://github.com/izimobil/polib/blob/master/docs/quickstart.md Calculate and display the percentage of translated entries in a PO catalog. This provides a quick overview of translation progress. ```python import polib po = polib.pofile('path/to/catalog.po') print(po.percent_translated()) ``` -------------------------------- ### Create Simple Entry with Polib Source: https://github.com/izimobil/polib/blob/master/_autodocs/complete-api-example.md Demonstrates creating a basic PO entry with a message ID, string, comment, and occurrences. The output shows the formatted PO entry. ```python import polib entry = polib.POEntry( msgid='Welcome', msgstr='Bienvenue', comment='Shown on login page', occurrences=[('login.py', 42)] ) print(entry) ``` -------------------------------- ### Load and Process MO Files Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/MOEntry.md Demonstrates the typical usage of MOEntry by loading a compiled MO file and iterating through its entries. It also shows how to convert the MO file back to an editable PO format. ```python # Load from compiled MO file mo = polib.mofile('translations.mo') for entry in mo: assert isinstance(entry, polib.MOEntry) translation = entry.msgstr # Convert MO back to editable PO format mo.save_as_pofile('translations.po') po = polib.pofile('translations.po') for entry in po: assert isinstance(entry, polib.POEntry) # Now can edit comment, flags, etc. ``` -------------------------------- ### Get msgid with Context for POEntry Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/POEntry.md Retrieve the message ID, including its context if specified. This is used internally for unique entry identification. ```python entry1 = polib.POEntry(msgid='File') print(entry1.msgid_with_context) # 'File' entry2 = polib.POEntry(msgid='File', msgctxt='menu') print(entry2.msgid_with_context) # 'menu\x04File' ``` -------------------------------- ### Create New PO File and Add Entries Source: https://github.com/izimobil/polib/blob/master/_autodocs/complete-api-example.md Use this snippet to create a new, empty PO file, set metadata, and add translation entries. ```python import polib # Create empty PO file po = polib.POFile() # Set metadata po.metadata = { 'Project-Id-Version': 'MyApp 1.0', 'Report-Msgid-Bugs-To': 'bugs@example.com', 'PO-Revision-Date': '2024-01-20 14:00+0100', 'Last-Translator': 'John Doe ', 'Language-Team': 'French ', 'Language': 'fr', 'MIME-Version': '1.0', 'Content-Type': 'text/plain; charset=UTF-8', 'Content-Transfer-Encoding': '8bit', 'Plural-Forms': 'nplurals=2; plural=(n != 1);', } # Add entries po.append(polib.POEntry(msgid='Hello', msgstr='Bonjour')) po.append(polib.POEntry(msgid='Goodbye', msgstr='Au revoir')) # Save po.save('fr.po') ``` -------------------------------- ### Get Translation Percentage Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/POFile.md Calculates and displays the percentage of translated entries in a PO file. Obsolete and fuzzy entries are excluded from the count. ```python po = polib.pofile('translations.po') print(f"Translation status: {po.percent_translated()}%") ``` -------------------------------- ### Get Obsolete Entries from POFile Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/POFile.md Retrieves a list of all entries marked as obsolete. Use this to find translations that are no longer present in the source code. ```python po = polib.pofile('translations.po') print(f"Obsolete entries: {len(po.obsolete_entries())}") ``` -------------------------------- ### Create Entry with Context using Polib Source: https://github.com/izimobil/polib/blob/master/_autodocs/complete-api-example.md Illustrates creating PO entries with context (msgctxt) to differentiate between identical msgids. It prints the context, message ID, and its translation for each entry. ```python import polib # Without context, these would collide: entries = [ polib.POEntry(msgid='File', msgctxt='menu', msgstr='Fichier'), polib.POEntry(msgid='File', msgctxt='noun', msgstr='Dossier'), polib.POEntry(msgid='File', msgctxt='verb', msgstr='Classer'), ] for entry in entries: print(f"{entry.msgctxt}: {entry.msgid} → {entry.msgstr}") ``` -------------------------------- ### Get PO File Representation (__unicode__) Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/MOEntry.md Returns the entry formatted as it would appear in a PO file. Used for display and debugging purposes. ```python def __unicode__(self, wrapwidth=78) -> str: ``` -------------------------------- ### Configure PO File Loading with Custom Class Source: https://github.com/izimobil/polib/blob/master/_autodocs/configuration.md Instantiate PO files using a custom class by providing a compatible class (inheriting from _BaseFile) to the 'klass' parameter. This allows for extended functionality. ```python class CustomPOFile(polib.POFile): def custom_method(self): return "custom" po = polib.pofile('file.po', klass=CustomPOFile) assert po.custom_method() == "custom" ``` -------------------------------- ### Get Translated Entries (MOFile) Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/MOFile.md Returns all entries in the MO file, as all entries are considered translated. This method exists for interface compatibility with POFile. ```python mo = polib.mofile('translations.mo') entries = mo.translated_entries() ``` -------------------------------- ### Load Compiled MO File and Convert to PO Source: https://github.com/izimobil/polib/blob/master/_autodocs/complete-api-example.md Loads a compiled MO (binary) file and demonstrates how to access its entries. It also shows how to convert the MO file back into an editable PO format. ```python import polib # Load binary MO file mo = polib.mofile('translations.mo') # Access entries (no metadata or comments in MO) for entry in mo: print(f"{entry.msgid} → {entry.msgstr}") # Convert back to editable PO format mo.save_as_pofile('translations_out.po') ``` -------------------------------- ### POEntry.fuzzy Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/POEntry.md Get or set the fuzzy flag for a POEntry. The fuzzy flag indicates that a translation needs review and is stored internally within the flags list. ```APIDOC ## POEntry.fuzzy ### Description Get or set the fuzzy flag. Fuzzy entries indicate translations that need review. The fuzzy flag is stored in the flags list but accessed as a boolean property. ### Method `@property` for getting, `@fuzzy.setter` for setting. ### Parameters #### Setter Parameters - **value** (bool) - The boolean value to set the fuzzy flag to. ### Example ```python entry = polib.POEntry(msgid='test', msgstr='test') # Get fuzzy status if entry.fuzzy: print("Translation needs review") # Set fuzzy flag entry.fuzzy = True # Adds 'fuzzy' to flags list # Clear fuzzy flag entry.fuzzy = False # Removes 'fuzzy' from flags list ``` ``` -------------------------------- ### Create Simple MOEntry Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/MOEntry.md Instantiate a basic MOEntry with a message ID and its translation. This is useful for creating simple, direct translations. ```python import polib # Simple MO entry entry = polib.MOEntry( msgid='Hello', msgstr='Bonjour', ) ``` -------------------------------- ### Get Fuzzy Entries from POFile Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/POFile.md Retrieves a list of all entries marked as fuzzy, excluding obsolete ones. Useful for identifying translations that require review. ```python po = polib.pofile('translations.po') for entry in po.fuzzy_entries(): print(f"Fuzzy: {entry.msgid}") ``` -------------------------------- ### Get Untranslated Entries (MOFile) Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/MOFile.md MO files contain no untranslated entries, so this method always returns an empty list. It exists for compatibility with POFile. ```python mo = polib.mofile('translations.mo') untranslated = mo.untranslated_entries() ``` -------------------------------- ### POEntry with Flags Source: https://github.com/izimobil/polib/blob/master/_autodocs/types.md Demonstrates how to initialize a POEntry with a list of flags, such as 'c-format' and 'python-format', to specify string formatting types. The 'fuzzy' attribute can be checked to determine if a translation requires review. ```python entry = polib.POEntry( msgid='User %s logged in', msgstr='Utilisateur %s connecté', flags=['c-format', 'python-format'] ) if entry.fuzzy: print("Needs review") ``` -------------------------------- ### Create and Save Translation File (Python) Source: https://github.com/izimobil/polib/blob/master/_autodocs/README.md Create a new PO file, set metadata, add a translation entry with occurrences, and save it to disk. ```python import polib po = polib.POFile() po.metadata = { 'Project-Id-Version': 'MyApp 1.0', 'Language': 'fr', 'Content-Type': 'text/plain; charset=UTF-8', } entry = polib.POEntry( msgid='Hello', msgstr='Bonjour', occurrences=[('main.py', 10)] ) po.append(entry) po.save('translations.po') ``` -------------------------------- ### Get Translation Percentage (MOFile) Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/MOFile.md MO files contain only translated messages, so this method always returns 100. It exists for interface compatibility with POFile. ```python mo = polib.mofile('translations.mo') percent = mo.percent_translated() ``` -------------------------------- ### Get msgid with Context (msgid_with_context) Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/MOEntry.md Returns msgctxt\x04msgid if context exists, otherwise returns msgid. This property is useful for retrieving the message identifier along with its context. ```python @property def msgid_with_context(self) -> str: ``` -------------------------------- ### MOFile Constructor Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/MOFile.md Initializes a MOFile object. It can be initialized with a path to a .mo file, file contents, or as an empty object. ```APIDOC ## MOFile Constructor ```python def __init__(self, *args, **kwargs) ``` ### Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | mofile | str | None | Path to .mo file or file contents (bytes) | | fpath | str | None | File path (alternative to mofile) | | wrapwidth | int | 78 | Line wrap width (kept for interface compatibility) | | encoding | str | utf-8 | Character encoding | | check_for_duplicates | bool | False | Raise error on duplicate entries | ### Example ```python import polib # Create empty MO file mo = polib.MOFile() mo.encoding = 'utf-8' # Add entries entry = polib.MOEntry( msgid='Hello', msgstr='Bonjour' ) mo.append(entry) # Save as binary mo.save('translations.mo') ``` ``` -------------------------------- ### Get Fuzzy Entries (MOFile) Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/MOFile.md MO files contain no fuzzy entries as they are not compiled. This method always returns an empty list and exists for compatibility with POFile. ```python mo = polib.mofile('translations.mo') fuzzy = mo.fuzzy_entries() ``` -------------------------------- ### Saving PO File in Different Representations Source: https://github.com/izimobil/polib/blob/master/_autodocs/ARCHITECTURE.md Illustrates the Strategy pattern for saving PO files in various formats. Choose the appropriate repr_method for text or binary output. ```python po.save(fpath, repr_method='__unicode__') # PO text ``` ```python po.save(fpath, repr_method='to_binary') # MO binary ``` -------------------------------- ### POFile Constructor Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/POFile.md Initializes a POFile object. It can be used to create a new PO file or load an existing one from a file path or string content. ```APIDOC ## POFile Constructor ### Description Initializes a POFile object. It can be used to create a new PO file or load an existing one from a file path or string content. ### Parameters #### Path Parameters - **pofile** (str) - None - Path to the .po/.pot file, or file contents as string - **fpath** (str) - None - File path (alternative to pofile) #### Query Parameters - **wrapwidth** (int) - 78 - Line wrap width for output formatting - **encoding** (str) - utf-8 - Character encoding to use - **check_for_duplicates** (bool) - False - Raise error when adding duplicate msgid entries ### Example ```python import polib # Create empty PO file po = polib.POFile() po.metadata = { 'Project-Id-Version': '1.0', 'Content-Type': 'text/plain; charset=UTF-8', } # Add entries entry = polib.POEntry( msgid='Hello', msgstr='Bonjour', occurrences=[('main.py', 10)] ) po.append(entry) # Save to file po.save('translations.po') ``` ``` -------------------------------- ### Create POEntry with Plural Forms Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/POEntry.md Example of creating a POEntry that supports plural translations. This involves defining msgid_plural and msgstr_plural, where msgstr_plural is a dictionary mapping indices to translations. ```python entry = polib.POEntry( msgid='One file', msgid_plural='%d files', msgstr_plural={ 0: 'Un fichier', 1: '%d fichiers' } ) ``` -------------------------------- ### Create Entry with Plural Forms using Polib Source: https://github.com/izimobil/polib/blob/master/_autodocs/complete-api-example.md Shows how to create a PO entry that supports plural forms, including singular and plural message IDs and a dictionary of plural translations. It prints the singular, plural, and translation details. ```python import polib entry = polib.POEntry( msgid='One file', msgid_plural='%d files', msgstr_plural={ 0: 'Un fichier', 1: '%d fichiers' }, occurrences=[('files.py', 10)] ) print(f"Singular: {entry.msgid}") print(f"Plural: {entry.msgid_plural}") print(f"Translations: {entry.msgstr_plural}") ``` -------------------------------- ### Get and Set Fuzzy Flag for POEntry Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/POEntry.md Access the fuzzy flag to determine if a translation needs review. Setting this property modifies the entry's flags list. ```python entry = polib.POEntry(msgid='test', msgstr='test') # Get fuzzy status if entry.fuzzy: print("Translation needs review") # Set fuzzy flag entry.fuzzy = True # Adds 'fuzzy' to flags list # Clear fuzzy flag entry.fuzzy = False # Removes 'fuzzy' from flags list ``` -------------------------------- ### Run Tests with Shell Script Source: https://github.com/izimobil/polib/blob/master/docs/contributing.md Execute the test suite using the provided shell script. Ensure you are in the polib directory. ```shell $ cd /path/to/polib/ $ ./runtests.sh ``` -------------------------------- ### Get Obsolete Entries (MOFile) Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/MOFile.md MO files contain no obsolete entries as they are removed during compilation. This method always returns an empty list and exists for compatibility with POFile. ```python mo = polib.mofile('translations.mo') obsolete = mo.obsolete_entries() ``` -------------------------------- ### Batch Processing with Configuration Source: https://github.com/izimobil/polib/blob/master/_autodocs/configuration.md Load multiple PO files efficiently using a shared configuration dictionary for batch processing. This is useful for applying consistent settings across many files. ```python import polib # Configuration for batch processing CONFIG = { 'wrapwidth': 100, 'encoding': 'utf-8', 'check_for_duplicates': True } def load_batch(files): results = [] for filepath in files: po = polib.pofile(filepath, **CONFIG) results.append(po) return results pofiles = load_batch(['es.po', 'fr.po', 'de.po']) ``` -------------------------------- ### Get Translation Statistics (Python) Source: https://github.com/izimobil/polib/blob/master/_autodocs/README.md Calculate and print various statistics for a PO file, including total entries, translated count, fuzzy count, and translation progress percentage. ```python import polib po = polib.pofile('translations.po') print(f"Total: {len(po)}") print(f"Translated: {len(po.translated_entries())}") print(f"Fuzzy: {len(po.fuzzy_entries())}") print(f"Untranslated: {len(po.untranslated_entries())}") print(f"Obsolete: {len(po.obsolete_entries())}") print(f"Progress: {po.percent_translated()}%") ``` -------------------------------- ### Convert Between PO and MO File Formats Source: https://github.com/izimobil/polib/blob/master/_autodocs/complete-api-example.md This snippet demonstrates how to compile PO files into MO format and decompile MO files back into PO format. It also shows creating and saving MO data directly. ```python import polib # PO to MO (compile) po = polib.pofile('translations.po') po.save_as_mofile('translations.mo') # MO to PO (decompile) mo = polib.mofile('translations.mo') mo.save_as_pofile('translations_out.po') # Create MO directly and save po = polib.POFile() po.append(polib.POEntry(msgid='test', msgstr='test')) binary_data = po.to_binary() with open('output.mo', 'wb') as f: f.write(binary_data) ``` -------------------------------- ### Get msgid with Context (msgid_with_context) Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/BaseEntry.md Retrieves the message ID, including the context if it is set. This property is crucial for uniquely identifying entries when context is present, using the EOT character as a separator. ```python @property def msgid_with_context(self) -> str ``` ```python entry = polib.POEntry(msgid='File', msgctxt='menu') print(entry.msgid_with_context) # 'menu\x04File' entry2 = polib.POEntry(msgid='File') print(entry2.msgid_with_context) # 'File' ``` -------------------------------- ### Configure PO File Loading with check_for_duplicates Source: https://github.com/izimobil/polib/blob/master/_autodocs/configuration.md Enable or disable duplicate entry checking during PO file creation. When True, attempting to add an entry with an existing msgid and msgctxt will raise a ValueError. ```python # Strict duplicate checking po = polib.POFile(check_for_duplicates=True) ``` ```python # Lenient (allows duplicates) po = polib.POFile(check_for_duplicates=False) ``` -------------------------------- ### Convert PO to MO and MO to PO Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/MOFile.md Use `save_as_mofile` to compile a PO file to MO format and `mofile` followed by `save_as_pofile` to decompile a MO file back to PO format. ```python # Convert from PO to MO (compile) po = polib.pofile('translations.po') po.save_as_mofile('translations.mo') # Convert from MO to PO (decompile) mo = polib.mofile('translations.mo') mo.save_as_pofile('translations.po') ``` -------------------------------- ### Get String Representation (__str__) Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/BaseEntry.md This method provides the string representation of the entry. In Python 3, it returns a unicode string, while in Python 2, it returns bytes encoded with the entry's encoding. ```python def __str__(self) -> str ``` -------------------------------- ### Load PO File and Iterate Entries Source: https://github.com/izimobil/polib/blob/master/_autodocs/complete-api-example.md Loads a PO file from the filesystem and iterates through its entries, printing metadata and entry details. Ensure the PO file exists at the specified path. ```python import polib # Load from file po = polib.pofile('translations/fr.po') # Get file metadata print(f"Language: {po.metadata.get('Language')}") print(f"Project: {po.metadata.get('Project-Id-Version')}") # Iterate all entries for entry in po: print(f"msgid: {entry.msgid}") print(f"msgstr: {entry.msgstr}") print(f"translated: {entry.translated()}") print(f"fuzzy: {entry.fuzzy}") print() ``` -------------------------------- ### Process Multiple PO Files in a Directory Source: https://github.com/izimobil/polib/blob/master/_autodocs/complete-api-example.md Iterates through all .po files in a specified directory, calculates translation statistics for each, and returns a summary. Useful for getting an overview of translation progress across many files. ```python import polib import os def process_all_translations(directory): stats = {} for filename in os.listdir(directory): if not filename.endswith('.po'): continue filepath = os.path.join(directory, filename) po = polib.pofile(filepath) stats[filename] = { 'total': len(po), 'translated': len(po.translated_entries()), 'untranslated': len(po.untranslated_entries()), 'fuzzy': len(po.fuzzy_entries()), 'percent': po.percent_translated(), } return stats stats = process_all_translations('translations/') for filename, info in stats.items(): print(f"{filename}: {info['percent']}% ({info['translated']}/{info['total']})") ``` -------------------------------- ### Load MO Catalog File Source: https://github.com/izimobil/polib/blob/master/docs/quickstart.md Load a compiled .mo catalog file. This is useful when the original .po file is unavailable. ```python import polib mo = polib.mofile('path/to/catalog.mo') print(mo) ``` -------------------------------- ### Get Ordered Metadata (Python) Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/BaseFile.md Retrieves metadata as a list of ordered (key, value) tuples. Standard keys are ordered first, followed by custom keys alphabetically. Useful for consistent metadata representation. ```python def ordered_metadata(self) -> list[tuple[str, str]] ``` ```python po = polib.POFile() po.metadata = { 'Language': 'es', 'Project-Id-Version': '1.0', 'Custom-Key': 'value', } ordered = po.ordered_metadata() # Returns: # [('Project-Id-Version', '1.0'), # ('Language', 'es'), # ('Custom-Key', 'value')] ``` -------------------------------- ### Iterating Over PO Entries Source: https://github.com/izimobil/polib/blob/master/_autodocs/ARCHITECTURE.md Demonstrates the Visitor pattern for iterating through entries in a PO file. This is the implicit way to traverse entries. ```python for entry in po: # Implicit visitor pattern print(entry) ``` -------------------------------- ### Polib Documentation File Organization Source: https://github.com/izimobil/polib/blob/master/_autodocs/README.md Illustrates the directory structure for the polib project's documentation files. ```text output/ ├── README.md (this file) ├── types.md (type definitions) ├── configuration.md (options and config) ├── errors.md (exceptions and errors) └── api-reference/ ├── module-functions.md (pofile, mofile, etc.) ├── POFile.md (POFile class) ├── POEntry.md (POEntry class) ├── MOFile.md (MOFile class) └── MOEntry.md (MOEntry class) ``` -------------------------------- ### Get PO File Representation (__unicode__) Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/BaseEntry.md This method returns the string representation of the entry in the PO file format. It handles context, plural forms, and obsolete entries. Specify wrapwidth for line wrapping. ```python def __unicode__(self, wrapwidth=78) -> str ``` -------------------------------- ### Detect and Specify Encoding for PO Files Source: https://github.com/izimobil/polib/blob/master/_autodocs/complete-api-example.md Demonstrates how to automatically detect the encoding of a PO file and how to load a PO file with a specific encoding, including a fallback mechanism. ```python import polib # Auto-detect encoding encoding = polib.detect_encoding('file.po') print(f"Detected encoding: {encoding}") # Load with specific encoding po = polib.pofile('file.po', encoding='iso-8859-1') # Load with fallback try: po = polib.pofile('file.po', encoding='cp1252') except LookupError: po = polib.pofile('file.po') # Auto-detect ``` -------------------------------- ### Open File in Binary Mode (Python) Source: https://github.com/izimobil/polib/blob/master/_autodocs/ARCHITECTURE.md Use this to open a file for writing in binary mode. No encoding is needed as data is treated as raw bytes. ```python open(path, 'wb') # No encoding needed ``` -------------------------------- ### POEntry with Message Context (msgctxt) Source: https://github.com/izimobil/polib/blob/master/_autodocs/types.md Illustrates how to use msgctxt to differentiate between identical msgids that have different meanings in various parts of an application, like 'menu' or 'button'. The combined context and msgid are accessible via msgid_with_context. ```python # Without context, these would collide: menu_file = polib.POEntry(msgid='File', msgctxt='menu', msgstr='Fichier') button_file = polib.POEntry(msgid='File', msgctxt='button', msgstr='Dossier') # Context is included in msgid_with_context: print(menu_file.msgid_with_context) # 'menu\x04File' print(button_file.msgid_with_context) # 'button\x04File' ``` -------------------------------- ### Save POFile as MO File Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/POFile.md Demonstrates saving a PO file in the compiled MO (Machine Object) binary format, which is used by gettext. ```python po = polib.pofile('translations.po') po.save_as_mofile('translations.mo') ``` -------------------------------- ### Load PO Catalog from String Source: https://github.com/izimobil/polib/blob/master/docs/quickstart.md Load a .po catalog directly from a string variable. Useful when the catalog content is available in memory. ```python import polib po_str = ''' msgid "" msgstr "" "Project-Id-Version: django\n" msgid "foo" msgstr "bar" ''' po = polib.pofile(po_str) ``` -------------------------------- ### mofile function Source: https://github.com/izimobil/polib/blob/master/docs/api.md Loads a MO file from the specified path. ```APIDOC ## The `mofile` function Loads a MO file from the specified path. ``` -------------------------------- ### MOFile List Operations Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/MOFile.md Demonstrates common list operations such as iteration, indexed access, length retrieval, membership testing, and modification (append, insert). Assumes 'entry' is a valid MO entry object. ```python mo = polib.mofile('translations.mo') # Iterate for entry in mo: print(entry.msgid, entry.msgstr) # Access by index first = mo[0] # Length count = len(mo) # Membership test (by msgid and context) if entry in mo: print("Found") # List operations mo.append(entry) mo.insert(0, entry) ``` -------------------------------- ### Create Compatible Entries for POEntry and MOEntry Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/MOEntry.md This function demonstrates how to create entries that are compatible with both POEntry and MOEntry constructors. While MOEntry ignores metadata like comments and occurrences, accepting these parameters allows for generic code that can handle both types. ```python def create_entry(msgid, msgstr, **metadata): # This works for both POEntry and MOEntry return polib.MOEntry( msgid=msgid, msgstr=msgstr, comment=metadata.get('comment', ''), occurrences=metadata.get('occurrences', []) ) # Creates POEntry with metadata po_entry = polib.POEntry( msgid='test', msgstr='test', comment='developer note' ) # Creates MOEntry ignoring metadata mo_entry = polib.MOEntry( msgid='test', msgstr='test', comment='developer note' # Ignored ) ``` -------------------------------- ### Create POEntry with Optional Parameters Source: https://github.com/izimobil/polib/blob/master/_autodocs/configuration.md Instantiate a POEntry object with all available optional parameters. Useful for creating complex entries programmatically. ```python entry = polib.POEntry( msgid='', msgstr='', msgid_plural='', msgstr_plural={}, msgctxt=None, comment='', tcomment='', occurrences=[], flags=[], previous_msgctxt=None, previous_msgid=None, previous_msgid_plural=None, linenum=None, obsolete=False, encoding='utf-8' ) ``` -------------------------------- ### POFile/MOFile Instance Configuration Source: https://github.com/izimobil/polib/blob/master/_autodocs/configuration.md Configures attributes of POFile and MOFile instances directly, affecting output formatting, encoding, duplicate checking, and file path management. ```APIDOC ## File-Level Attributes ### POFile/MOFile Instance Configuration Configures attributes of POFile and MOFile instances directly, affecting output formatting, encoding, duplicate checking, and file path management. ```python po = polib.POFile( wrapwidth=78, encoding='utf-8', check_for_duplicates=False ) # Modify after creation po.wrapwidth = 100 po.encoding = 'iso-8859-1' po.fpath = '/path/to/file.po' po.check_for_duplicates = True ``` | Attribute | Type | Description | |-----------|------|-------------| | wrapwidth | int | Output line wrap width | | encoding | str | Character encoding | | check_for_duplicates | bool | Validate unique msgids | | fpath | str | File path for save operations | | header | str | File header comments | | metadata | dict | File metadata | | metadata_is_fuzzy | int | Fuzzy flag for metadata | ``` -------------------------------- ### PO File Entry Formatting Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/BaseEntry.md Illustrates the standard gettext PO file format for single and plural messages. This format is followed by the string output of BaseEntry objects. ```plaintext msgctxt "context" (if msgctxt set) msgid "message" msgid_plural "plural form" (if msgid_plural set) msgstr "translation" (or msgstr[0], msgstr[1], etc. for plural) ``` ```plaintext msgid "" "Line 1\n" "Line 2" msgstr "" "Ligne 1\n" "Ligne 2" ``` -------------------------------- ### Iterating and Accessing Entries in POFile Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/POFile.md Demonstrates how to iterate through entries in a POFile object and access individual entries by index. Assumes a POFile object named 'po' has been loaded. ```python po = polib.pofile('translations.po') # Iterate for entry in po: print(entry) # Index access first_entry = po[0] ``` -------------------------------- ### pofile function Source: https://github.com/izimobil/polib/blob/master/docs/api.md Loads a PO file from the specified path. ```APIDOC ## The `pofile` function Loads a PO file from the specified path. ``` -------------------------------- ### MOEntry Constructor Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/MOEntry.md Initializes a new MOEntry object. It accepts various parameters to define the translation entry, including original message, translated string, plural forms, context, and metadata. ```APIDOC ## MOEntry Constructor ### Description Initializes a new MOEntry object with translation data. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **msgid** (str) - Required - The original untranslated message string - **msgstr** (str) - Required - The translated message string - **msgid_plural** (str) - Optional - Plural form of msgid - **msgstr_plural** (dict) - Optional - Plural translations {index: translation} - **msgctxt** (str) - Optional - Message context for disambiguation - **obsolete** (bool) - Optional - Whether entry is obsolete - **encoding** (str) - Optional - Character encoding - **comment** (str) - Optional - Ignored (accepted for compatibility) - **tcomment** (str) - Optional - Ignored (accepted for compatibility) - **occurrences** (list) - Optional - Ignored (accepted for compatibility) - **flags** (list) - Optional - Ignored (accepted for compatibility) - **previous_msgctxt** (str) - Optional - Ignored (accepted for compatibility) - **previous_msgid** (str) - Optional - Ignored (accepted for compatibility) - **previous_msgid_plural** (str) - Optional - Ignored (accepted for compatibility) ### Request Example ```python import polib # Simple MO entry entry = polib.MOEntry( msgid='Hello', msgstr='Bonjour', ) # Entry with context entry = polib.MOEntry( msgid='File', msgctxt='menu', msgstr='Fichier' ) # Entry with plural forms entry = polib.MOEntry( msgid='One file', msgid_plural='%d files', msgstr_plural={ 0: 'Un fichier', 1: '%d fichiers' } ) ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### to_binary Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/BaseFile.md Generates the binary representation of the file in MO format, including the header, sorted string table, and handling for plurals and contexts. ```APIDOC ## to_binary ### Description Get binary representation of file (MO format). Generates the compiled MO file format. This includes: - MO header with magic number and metadata - Sorted string table with keys and values - Plural form handling (msgid\0msgid_plural) - Context handling (context\x04msgid) ### Method ```python def to_binary(self) -> bytes ``` ### Returns **Type:** `bytes` The binary MO file representation. ### Example ```python po = polib.POFile() po.append(polib.POEntry(msgid='test', msgstr='test')) binary_data = po.to_binary() with open('output.mo', 'wb') as f: f.write(binary_data) ``` ``` -------------------------------- ### Save PO/MO Files with Representation Method Source: https://github.com/izimobil/polib/blob/master/_autodocs/configuration.md Use the repr_method parameter in the save() method to specify the output format. Use '__unicode__' for text (PO) format and 'to_binary' for binary (MO) format. ```python po = polib.POFile() # ... add entries ... # Save as text po.save('output.po', repr_method='__unicode__') # Save as binary (MO format) po.save('output.mo', repr_method='to_binary') ``` -------------------------------- ### Convert to Binary MO Format (Python) Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/BaseFile.md Generates the binary MO file representation, including the header, sorted string table, and handling for plurals and contexts. This is used for creating compiled message catalogs. ```python def to_binary(self) -> bytes ``` ```python po = polib.POFile() po.append(polib.POEntry(msgid='test', msgstr='test')) binary_data = po.to_binary() with open('output.mo', 'wb') as f: f.write(binary_data) ``` -------------------------------- ### Save POFile to Disk Source: https://github.com/izimobil/polib/blob/master/_autodocs/api-reference/POFile.md Shows how to save changes to a PO file. It can save to a new file path or overwrite the original file if no path is specified. ```python po = polib.pofile('input.po') po[0].msgstr = 'Updated translation' po.save('output.po') # Save to new file po.save() # Save to original file ``` -------------------------------- ### Compile PO file to MO file Source: https://github.com/izimobil/polib/blob/master/docs/quickstart.md Convert a POFile object into its binary MO (Machine Object) format and save it to a specified file path. This is typically done for deployment. ```python po.save_as_mofile('/path/to/newfile.mo') ```