Multi language support in application [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm trying to create a little tool which also features a GUI. I want to offer different languages in the interface. That's why I think about writing all the strings in a file for each language and read the data while creating the gui. I'm worried about that this could takes alot of memory and decreasing performance.
Is there a good way to implement this?
Pseudocode example:
language_file = open(path)
title = language_file.title
text = language_file.text
button_text = language_file.btntext
window = tk.Tk()
la_title = tk.Label(window, text=title)
la_text = tk.Label(window, text=text)
btn = tk.Button(window, text=button_text, command=close_window)

1. Find a proper file Format.
Some Formats are better suited than others. You Need something where you can define something like a label and for each language the correpsonding value. You could try the csv Format.
2. Loading the data into a python object
When you have created your file with all your data you can load it at the start of your program into a python object. this shouldn't take too Long when your file isn't huge and I mean huge. You open the file and load in some python opject to work with it.
3. Creating a proper python object.
What you want is something like a dictionary. You have a label which is the key and a value dependent on the selected language. So you could either have for each language a dictionary. or a more nested ditionary.
For better Access I would create a class to handle all this.
Possible Things that can make Things easier. (I will expand this part later on. And add more details)
You could:
Override the __getattr__ method so you can write: Language.header
Extend the __dict__ of the the class with the language dictionary: Language.header is possible
write a function: Language.get_text("Header") or Language.get_text("Header", "english") or ...
Dictionary example (expanding __dict__)
class Language:
def __init__(self, texts):
self.texts = Texts
print(dir(self)) # just for debug
# Magic part
self.__dict__.update(self.texts)
print(dir(self)) # just for debug. Note the last entries
#staticmethod
def from_file(path, language):
# comment the open part out if you just want to test this example without a file
with open(path, r) as f:
pass # Read content. Get all words of language
texts = {"header": "My header", "label_username": "Username"}
return Language(texts)
l = Language.from_file("Some path to a file", "English")
print(l.header)
print(l.label_username)

Related

How to automate saving constants? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last year.
Improve this question
I am in the process of running experiments, and ideally, once all of my code is working, the only parameters that will need to be changed will all be present in one file. My initial idea was to store these parameters in a JSON file:
{
"param1": 1,
"param2": "string parameter"
}
Where, obviously, I have many more than 2 parameters. This turns out to be a nightmare, as my IDE will not guess any of the parameters, which massively slows down my programming as I generally feel obligated to create local variables for every constant that I need in the current function that I'm working in. This results in a lot of unnecessary code (but local to that function, it is significantly more convenient than trying to index the JSON object).
My next thought was then: store the constants in a file like:
PARAM1 = 1
PARAM2 = 'string parameter'
The problem with this is that I'd like to store the parameters with experimental results so that I can look back to see which parameters were specified to produce those results.
Beyond this, my thought is to use a dataclass (probably one with frozen=True), as those can be converted to a dictionary. However, I do not need access to an instance of the class, just the constants within it.
Another thought is to use a class with static variables:
class ExperimentalMetaData:
param1 = 1
param2 = "string parameter"
Which can be converted to a dict with vars(ExperimentalMetaData), except this will contain additional keys that should be popped off before I go about storing the data.
My question is: what is the best way to store constants in python such that they can be saved to a JSON file easily, and also be easily accessed within my code?
If you want to be able to recall different versions of inputs, give them a version
This allows you to create JSON-like input files and keep a collection of parsers which can parse them if you make a breaking change
Here's a very simple example which is more sustainable
class Parser_v1_2(): pass
class Parser_v3_2(): pass
VERSION_PARSER_MAPPING = {
"1.2": Parser_v1_2,
"3.2": Parser_v3_2,
}
def parser_map(input_file):
with open(input_file) as fh:
input_json = json.load(fh)
# get version or optionally provide a default
version = input_json.get("version", "1.0")
# dynamically select parser
return VERSION_PARSER_MAPPING[version](input_json)
Split up your problems.
Storing the data
Serialise it to JSON or YAML (or even csv).
Getting the data
Have a module which reads your json and then sets the right values. Something like:
# constants.py
from json import load
data = load("dump.json")
const1: str = data["const1"]
const2: str = data["const2"]
const3: int = data["const3"]
# some_other_module.py
from constants import const1, const2 # IDE knows what they are
I'd only do this manually with vars in a module for a small (<20) number of vars I needed a lot and didn't want to wrap in some dictionary or the like. Otherwise I'd just use a dict in the module. Pre-populating the dict with keys and None and typehinting it will do the same job of getting autocomplete working.

Using comment #'s as decorations for better visual discernment - is this bad practice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I'm working on a very repetitive code. I'm using selenium to launch a webdriver to extrapolate javascript data generated by a PLC controller via its IP address. The script is a GUI that allows users to poll the data from the PLC, involving descriptive names, inputs, outputs, etc.
My question is: Is it bad practice, throughout the thousands of lines of code, to use the # as a visual in order to distinguish the code easier? Please look at the examples below:
Example 1 - Creating Headers
###################################################################
# List Definition for (AI) with the point name stored in index[0] #
###################################################################
self.ai_ain0_lst = ['Spindle FORCE']
self.ai_ain1_lst = ['PT-47']
self.ai_ain2_lst = ['PT-44']
self.ai_ain3_lst = ['LOAD CELL']
self.ai_ain4_lst = ['Ring Force Command']
self.ai_ain5_lst = ['Back Pressure Command']
self.ai_ain6_lst = ['PT-45']
self.ai_ain7_lst = ['PT-42']
Example 2 - Boxing in code
# Logo Image ##################################################
tech_logo = PhotoImage(file=path_to_folder + "tech_logo.png") #
image_label = Label(self, image=tech_logo) #
image_label.image = tech_logo #
image_label.grid(row=0, column=4, pady=10, padx=10, sticky=N) #
###############################################################
I still use #s appropriately throughout the code for others to follow along, but for the repetitive stuff I've been creating giant headers (Example 1), and indent them once to the left so I can collapse the code in my editor. Is this okay within the coding community? Frowned upon? Or does no one really care as long as the code works and has comments when necessary?
Since indentation is meaningful in python, you are asking for trouble by using indentation like this.
Python gives you packages, modules, classes, methods and functions to allow you to structure your code. Try refactoring your code into these structures so that your code, not just your text, is easy to understand.

Python Search and Scrape [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a problem I'd like to know if it's worth spending the time trying to solve with Python. I have a large CSV file of scientific names of fishes. I would like to cross-reference that CSV file with a large database of fish morphology information (www.fishbase.ca) and have the code return the maximum length of each fish. Basically, I need to create code that will search the fishbase website for each fish, then find the maximum length info on the page and return it to me in a CSV file. The last two parts are relatively straightforward, but the first part is where I'm stuck. Thanks in advance.
It looks like you can generate the url directly from the genus and species, ie
rainbow trout (oncorhynchus mykiss) becomes
http://www.fishbase.ca/summary/Oncorhynchus-mykiss.html
so something like
def make_url(genus, species):
return (
"http://www.fishbase.ca/summary/{}-{}.html"
.format(genus.title(), species.lower())
)
Looking at the page source, the html is severely unsemantic; while parsing html with regular expressions is evil and awful, I really think it's the easiest method in this case:
import re
fishlength = re.compile("max length : ([\d.]+) ([cm]{1,2})", re.I).search
def get_length_in_cm(html):
m = fishlength(html)
if m: # match found
value = float(m.group(1))
unit = m.group(2)
if unit == "cm":
return value
elif unit == "m":
return value * 100.
else:
raise ValueError("Unknown unit: {}".format(unit))
else:
raise ValueError("Length not found")
then grabbing each page,
import csv
import requests
from time import sleep
DELAY = 2
GENUS_COL = 4
SPECIES_COL = 5
with open("fish.csv") as inf:
next(inf) # skip header row
for row in csv.reader(inf):
url = make_url(row[GENUS_COL], row[SPECIES_COL])
# should add error handling, in case
# that page doesn't exist
html = requests.get(url).text
length = get_length_in_cm(html)
# now store the length value somewhere
# be nice, don't pound their site
sleep(DELAY)
So, in order to use the information in other web applications you will need to use an API to get hold of their data.
Fishbase.ca (or .org) does not have an official public-facing API. There is some chat in 2013 about creating a RESTful API which would be just the ticket for what you need, but this hasn't happened yet (don't hold your breath).
An alternative is using the name of the fish you need to lookup, dropping that into the URI (eg www.fishbase.ca/fish/Rainbow+Trout) and then using Xquery or similar to drill down the DOM to find the maximum length.
Unfortunately, fishbase does not have the sort of URIs needed for this method either, this is the URI for Rainbow Trout - uses an ID rather than a name to easily look up.
I would suggest looking into another data provider looking for either of these two APIs.
Regarding the second method: the site owners may not appreicate you using their website in this manner. Ask them beforehand if you can.

Assigning variable with other variable in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hey guys am new to python development..I am studying python on my way
I have just tested a simple code which includes assigning two variables with single at one line
Here is my snippet:
name = 1
somevariable = "hellow am new to python"
print somevariable[name]
And i got an output "e".
I did not understand what it means. I just tried out a random example .Is it allowed to do like this in python .or is it with arrays. Please help me to find an appropriate answer. Any help would be appreciated.
EDIt
Can we store a variable information to other variable in python
For eg
name = 1
age = 2
string = "yeah am a man"
name[age] = stringname = 1
My qus is that can we store the value 1 to age ?..AM new to python ..Sorry for the bad question
First of all you need to read basic of python first, because from your snippet clearly says that you don't know what is mutable and immutable object in python.
And for your question,this name[age] = stringname = 1 is not allowed.
First you will name Error for age after that you will get int object is not allowed for item assignment.
About list:
About Dictionary:
I'm not quite sure what you're trying to achieve, but it sounds a bit like you're trying to store multiple attributes (e.g name and age). If so, you could use a dict. e.g.
# initialise the dict
user = {}
# Add some data
user["name"] = "User"
user["age"] = 1
To retrieve the variables, just use e.g. user["name"]

How to add data to a list in the code while running [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Suppose i want to add something to
list = []
such that the value of list gets updated in the code it self.
In runtime:
list gets modified to
list =['hello','Dude']
How can i do so?
What i mean is, that there are real changes made to the List value in the .py file.
Judging from your comments to one of the other answers what you are looking for is a way to serialize and save an object to a file so you can reload it once you re-run the program. This is done using pickle.
An example of this can be found on stack overflow: How to save an object in Python:
import pickle
try:
with open('list.pk', 'rb') as input:
list = pickle.load(input)
except:
list = []
list.append('something')
print(list)
with open('list.pk', 'wb') as output:
pickle.dump(list, output, pickle.HIGHEST_PROTOCOL)
Just use append where ever you need it:
list = []
list.append('hello')
print list
list.append('Dude')
print list
Output:
['hello']
['hello', 'Dude']<
Easy way would be to create additional file and to store variables there.
Code:
list = []
f = open("list.txt", "r+")
for item in f:
list.append(str(item).rstrip())
f.write("Something")
f.close()
list.txt:
hello
Dude
list.txt after execution:
hello
Dude
Something
The only way to do it is rewriting the .py file.
You don't really want to do that even if it's indeed technically possible.
You should instead keep your data in a separate file, loaded when starting the program and saved back when exiting.
There are special modules for storing python values like e.g. shelve.
A very common alternative is storing the data in a format that can be understood even by other languages intead of python objects, e.g. in a relational database like sqlite.

Categories