Posts by nosklo • 5,801 points
236 posts
-
0
votes1
answer297
viewsA: Filter python list
lista_editada = [] # cria uma nova lista vazia nao_foram_editados = [] # outra para os que nao foram editados for grupo in lista_original: # para cada grupo da lista foi_editado =…
-
2
votes1
answer88
viewsA: Python - Compare Lists, using conditions to determine Start and End of Search
lista = ['BBB','AAA','CCC','DDD','EEE'] conjunto = {'AAA','BBB','CCC','DDD','EEE','FFF','GGG','EEE'} aaa_encontrado = False for item in lista: if item == "AAA": …
-
1
votes1
answer1271
viewsA: Saves float array in a txt file
If you saved with numpy.savetxt, must use numpy.loadtxt to carry: np.savetxt('A.txt', A, newline='\n') Afterward... A = np.loadtxt('A.txt')…
-
1
votes1
answer287
viewsA: moviepy: reduce video to 100mb
Unfortunately it is not easy to predict the size a compressed video will get before trying to compress it. This depends on the content of the video - videos where the image gets more static spend…
-
0
votes1
answer41
viewsA: Select lines by first digits, and average them per year
import csv, collections soma = collections.defaultdict(float) qtd = collections.defaultdict(int) with open('arquivo.csv', newline='') as f: cf = csv.DictReader(f,…
-
1
votes1
answer342
viewsA: Doubt how to scrape data like Python using Beautifulsoup <Table>
Your problem is that the data are not on the page. When accessing the page, a blank skeleton is loaded from where the data should be, and then the page runs javascript code that makes a separate…
-
0
votes1
answer1038
viewsA: Relationship Django Models
Use the parameter through of ManyToManyField to define a model that will serve as connection between the other two. In this model you can put additional data: class Item(models.Model): nome =…
-
1
votes1
answer54
viewsA: Take data from a page and go to the database
from app.mac import mac, signals from sqlalchemy import create_engine, Column, Integer, Unicode from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base engine…
-
0
votes1
answer55
viewsA: How to test if all elements are 2-element tuples
def testar(argumento): return ( isinstance(argumento, tuple) and all(isinstance(elemento, tuple) and len(elemento) == 2 and isinstance(elemento[0], str) and…
-
0
votes1
answer3268
viewsA: Python Back-end for Front-end
You can consult Sqlite3 data in Javascript? In fact yes.... sqlite has been compiled for javascript and is called sql.js. Can be downloaded here https://github.com/kripken/sql.js Small example of…
-
1
votes2
answers259
viewsA: Problem in Pickle library in Python
Your problem is in the name of your file. You called it pickle.py however pickle already and a module name that comes with python, so it’s getting confused what you mean by import pickle. Rename…
-
2
votes1
answer63
viewsA: Slice an array
The problem is that the way you’re calculating, x2 turns into a two-dimensional matrix, with the outermost dimension having only 1 element. Thus, x2[1:] and x2[:-1] do not return anything, because…
-
0
votes1
answer383
viewsA: Python Telnetlib connect port other than 23
There’s a problem with your code, which is the use of tn.open() after creating the instance with server and port name. If you created the server like this: tn = telnetlib.Telnet(HOST, PORT, TIMEOUT)…
-
0
votes1
answer276
viewsA: Write multiple csv files in Python
This function below finds a unique name for the file. It keeps adding 001, 002 etc until you find a number that doesn’t exist yet. def acha_proximo_nome(nome_arquivo): if not…
-
2
votes2
answers867
viewsA: Replace string with regex in python 3
The problem is in your regex... '(/.*)' means "one bar and all that comes after"! I don’t know what you want to do... If you want to take http try using this regex: r'https?://' EDIT: Now that you…
-
0
votes1
answer352
viewsA: How to make server threads in Python?
The way you’re doing, it’s calling the function ServerWorker.worker() first and then trying to start the thread with the result of this function (which in this case is None since it does not return…
-
2
votes3
answers139
viewsA: Lists within lists: Even when sliced, there is connection between lists
A more detailed explanation. Each list is a separate object. there is no "list a" or "list b". In python, unlike many other languages, variables are only names that if refer to objects. Let’s go…
-
2
votes1
answer61
viewsA: I want to "capture" the path and use it in another program
When you use graphical user interface, usually the script that runs the mainloop() becomes the "main", so it is he who should import the other script. For this you must encapsulate the functionality…
-
4
votes2
answers3831
viewsA: Dataframe Pandas - Calculate column based on other
Create a function that determines the class you want to place in the column: def acha_classe(registro): if registro['COMEDY'] > registro['CRIME']: return 'COMEDY' elif registro['COMEDY'] <…
-
0
votes1
answer343
viewsA: 'Botfalante' error Object is not callable
resp = Bot.pensa(frase) AttributeError: 'BotFalante' object has no attribute 'pensa' The object Bot is an instance of the class BotFalante. If you are trying to access a method .pensa(...) in that…
-
1
votes1
answer14224
viewsA: Typeerror: list indices must be integers or Slices, not str
I will have to use my crystal ball, because it is missing important part of the code, and the error message is incomplete. In that part of the code: for infos in transaction: gravar.append((…
-
1
votes1
answer83
viewsA: How do I display an image according to a given Number and this number is by Random in python?
Instead of using a variable for each image, use an indexable structure such as lists or dictionaries. For numbers from scratch, a list would do, but I prefer to use dictionaries, in case I need more…
-
3
votes1
answer1303
viewsA: Removing elements from a list
The list is a direct sequence of values, they are not associated with the index. Then, when removing an element from the middle of the list, all elements in front are "shifted". For example, if you…
-
6
votes3
answers1537
viewsA: Calculate the age group of 10 people within a repeat loop?
lacked the comparison operator < between number and variable elif 18 pessoas <= 65: should be elif 18 < pessoas <= 65: The same for all other comparisons made. EDIT: I believe that you…
-
2
votes2
answers5334
viewsA: How to check the versions of the modules installed in Python?
There is no 100% deterministic way for a module to inform its version. There are conventions and suggestions. THE PEP 8 suggests here that a module variable called __version__ to store the version,…
-
4
votes1
answer1971
viewsA: Import and manipulate json in Python
Your file structure is a variant of JSON, called JSON Lines. The file extension should be .jsonl. It’s a very simple format, exactly like JSON, but instead of a single JSON throughout the file, this…
-
2
votes1
answer58
viewsA: What is the difference between the wraps and update_wrapper functions of the funtools module
In fact of the two functions, the only one that does anything is the update_wrapper. She copies, among other things, __module__, __name__, __qualname__, __annotations__ and __doc__ from one function…
-
2
votes1
answer978
views -
0
votes1
answer1773
viewsA: How to pass data from one input to another with HTML and Python?
Use a session variable to store the id: request.session['id_cadastro'] = algum_tipo_de_id then on the other page you can read the id id_atual = request.session.get('id_cadastro', None) if not…
-
1
votes1
answer330
viewsA: How can I keep the private and publish key for later use? Since the program always generates different keys?
Extract bytes to be saved from your private key: binary_data = private_key.private_bytes( encoding=serialization.Encoding.PEM, # codificacao format=serialization.PrivateFormat.PKCS8, # formato…
-
4
votes1
answer1172
viewsA: What are file descriptors and directories?
The module os gives access to certain low-level resources, rarely used in standard python programming. An example are these functions that deal directly with file and directory descriptors. On…
-
0
votes1
answer141
viewsA: Is it possible to use Sqlite3 on Android using the Qpython3 app?
It is possible from Qpython version 1.0, but you need to define where to save the file. The error is indicating that you are not allowed to save in the place where you tried: conexao =…
-
0
votes1
answer180
viewsA: I have a question in the kivy + sql text_input
The problem is in the way you are entering the name in the bank: nome = self.root.ids.usuario.textinput ... nome.execute('INSERT nome FROM cadastro') results = cadastro.execute(nome).fetchall()…
-
0
votes1
answer517
viewsA: Pandas dataframe.Loc() does not find the record
The problem is that .set_index() does not change the content of DataFrame, and yes, a new one returns DataFrame with the changed index. Change dre.set_index('Conta') To dre = dre.set_index('Conta')…
-
0
votes1
answer92
viewsA: :python3 Tkinter Requests: Temporary lock in get('url') with request module!
The problem is that this single line makes the request and downloads the entire file, so Tkinter doesn’t have time to update the interface, because it goes too long without calling the…
-
0
votes1
answer103
viewsA: Problems with the Python library
That library comtypes is a lightweight package for access to COM in python, allowing you to create and register or access COM interfaces in your script. WITH IT MEANS Component Object Model, and is…
-
0
votes1
answer85
viewsA: Find the last matrix position
Currently your maximum right drive number is fixed at 280; you need to calculate this value dynamically using the right-most enemy as the base. 700 is the width of the screen, so change the line if…
-
0
votes3
answers1808
viewsA: When should I use "Return" or "print" in a function?
Your confusion comes from the python suit, at command prompt (REPL) >>>, automatically print the returned value. This does not normally occur, only when you are executing commands at the…
-
5
votes2
answers67
viewsA: How to relate two lists, obtaining the value of one through the maximum of the other?
There is no need to store all teams and their number of goals - just store only one: the largest you’ve seen so far - if, during running, you find a larger number of goals than you’ve seen before,…
-
1
votes2
answers2508
viewsA: Difference between commands to stop execution
In fact, there are only 3 ways to finish the application: Normally, i.e., the code run until the end of the main script; Occur a exception which is not treated with try/except, causing an error…
-
0
votes1
answer492
viewsA: Python - scroll through a list - replace word within word (.docx)
Your code is almost fine, just a few things that are reversed. The logic is this, first, do the for in the list, because each element in the list means a new file that you will generate. In each…
-
0
votes1
answer1242
viewsA: Change the download name Selenium python
No, this is not possible. What you can do is create a temporary folder using tempfile.mkdtemp() and spend it on your default_directory... So the browser will save the files in it. Then you move the…
-
2
votes1
answer397
viewsA: Tweeter
You’re getting the tweets sent by the person because that’s what the method .user_timeline() ago... On Tweeter there is no sending tweets for someone. What exists is mentions or direct message. To…
-
1
votes2
answers78
viewsA: Check if directory 'B' is inside directory 'A'
def subdir(pai, filho): return os.path.abspath(filho).startswith(os.path.abspath(pai) + os.path.sep) Note that this function does not check whether directories exist, only if one is contained in the…
-
2
votes1
answer222
viewsA: I want to scrap a page, but I can’t get a text that has " " on it
Your problem is that the price does not actually exist on the page! The cold spot pages, as well as many others on the internet, are made available without the price, and only after this price is…
-
1
votes2
answers353
viewsA: How can I encrypt a user input text? giving error
Cryptography only works with bytes. That’s what the lyrics mean b at the beginning of the literal. When reading a user string it comes to str, and you need to convert to bytes in order to encrypt.…
-
2
votes1
answer98
viewsA: str Object has no attribute 'Encrypt'
It’s missing code there - You try to call public_key.decrypt() but public_key is a str - a standard type already defined in python - and none str has the methods decrypt nor encrypt, so there’s one…
-
0
votes2
answers37
viewsA: The program must consider all possible validations. That is, it cannot be allowed to access, delete or change a non-existent position from the list
Use a while that repeats typing until the user enters an existing position: while True: posicao = int(input('digite a posicao: ')) if 0 <= posicao < len(lista): break print('A posição {} não…
-
1
votes4
answers1713
viewsA: Removing lines from a numpy array
I prefer it this way: >>> sua_array = np.array([[ 1, 1, 1], [ 2, 2, 2], [ 3, 3, 3], [ 4, 4, 4], [ 5, 5, 5], \ [ 6, 6, 6], [ 7, 7, 7], [ 8, 8, 8], [ 9, 9, 9], [10, 10, 10], [11, 11, 11], \…
-
0
votes1
answer257
viewsA: Program lock when executing function. Tkinter + Python3
It is necessary to call root.update() from time to time to update the graphical screen of tkinter... If you don’t call this function once in a while, python will only be calculating md5 within its…