Posts by britodfbr • 688 points
73 posts
-
-1
votes1
answer67
viewsQ: What does an expression between parentheses mean followed by an expression between brackets?
I found this code: nums = [1,2,3,4,5,6,7,8] round(sum(a ** (2, 0.5)[a % 2] for a in nums), 2) My doubt is in this passage (2, 0.5)[a % 2], what name? How it works?…
-
0
votes4
answers416
viewsA: How to remove multiple blank lines in sequence with vim?
:g/^$/:delete or :g/^$/d g = global, whole document ^ = beginning of the line $ = end of the line Note: the $ standard means everything that has nothing between the beginning and end of the line d |…
-
0
votes2
answers1966
viewsA: Pandas Soma Condicional
df1.groupby(by=['Key']).sum() Value Key a 19.6 b 16.0 c 16.8
-
0
votes0
answers158
viewsQ: pandas.DataFrame.Loc
I have the following situation: d= {'files': ['f1.txt', 'f2.txt', 'f3.txt'], 'url': ['url1', 'url2', 'url3'], 'nav': [False, True, False]} df = pd.DataFrame(d) files url nav 0 f1.txt url1 False 1…
-
0
votes2
answers277
viewsA: Bashscript. How to execute a command at a given time?
To perform this type of task, cron (crontab|crond) is used take a look at the first sample result I found on google: https://tecadmin.net/crontab-in-linux-with-20-examples-of-cron-schedule/…
-
0
votes1
answer99
viewsA: Pandas convert epoch str to datetime
I found this solution: ... # Tratamento de elementos Nulos df.fillna(value=float('nan'), inplace=True) df.replace('None', float('nan'), inplace=True) # Convert epoch to datetime tz Brazil df.mtime =…
-
-1
votes1
answer99
viewsQ: Pandas convert epoch str to datetime
Good afternoon, everyone. I need help converting types in pandas. Follow the information: I have CSV containing the Intel, a Bulletin field, ctime, mtime and the name of the files respectively,…
-
1
votes4
answers197
viewsA: Remove comment tag and your content in Beautifulsoup 4
This solution uses List Comprehension. from bs4 import BeautifulSoup, Comment soup = BeautifulSoup(html, 'html.parser') [x.parent.decompose() for x in soup.find_all(text=lambda x: isinstance(x,…
-
-1
votes1
answer221
viewsQ: How to validate if ternary operator was used in the implementation?
I want to validate through the TDD if in the implementation was applied ternary operators. How can I measure this situation? def par_impar(x): return "impar" if x % 2 else "par" Or this other?…
-
1
votes0
answers332
viewsQ: Pandas: How can I update values in dataframe?
I have two spreadsheets where one is updating the other. How can I update this data using pandas? Example, where 'b' updates 'a': a = {'campo': ['a', 'b', 'c'], 'valor': ["", None, 1]} b = {'campo':…
-
3
votes2
answers81
viewsQ: How to sort a string by initial fragment?
I need to order a string originating from the git tag -ln. 2019.3.0 Primeira versão totamente integrada com gitlab-ci 2019.3.0-dev0 Aplicado correções sugeridas por py3kwarn 2019.3.0-dev1 refatorado…
-
0
votes2
answers237
viewsA: How to get the name of the python function parent
Hello! I believe that using the resources of python for such a need will be more fruitful... The logging package, brings functionalities to record activities already implemented, fitting only to…
-
0
votes1
answer32
viewsQ: Python: How to apply mock in dataclass?
I have following code : import unittest import unittest.mock as mock from dataclasses import dataclass @dataclass class Config: system: str = platform.system().lower() class…
-
0
votes2
answers433
viewsA: recursive function with lists
I believe this implementation will meet your need! def subtrair(list1, list2): for i in list2: list1.remove(i) return list1
-
0
votes1
answer27
viewsA: unittest.mock: How can I use datetime.datetime.now with different calls in the same method?
I was successful with this: @patch('mypackage.dt') def test_metodo(self, mock_date): expected = ('2018', "2018-12-14 12:34:56") mock_date.today.return_value = mypackage.dt(2018, 12, 14, 12, 34, 56)…
-
0
votes1
answer27
viewsQ: unittest.mock: How can I use datetime.datetime.now with different calls in the same method?
How can I proceed with a mock test on datetime.datetime.now with different calls in the same method? In my test is returned the current date. Follow an example of the code, to facilitate help.…
-
0
votes1
answer549
viewsQ: Pandas: How to merge two data frames?
Good morning Everybody! I count on your help again. I have 2 CSV, as below: # f1.csv num ano 76971 1975 76969 1975 76968 1975 76966 1975 76964 1975 76963 1975 76960 1975 and # f2.csv num ano dou url…
-
2
votes1
answer52
viewsQ: HTML5/CSS3: How to fix an unordered list item at the end of all items
/* Nav retratil */ /*=================*/ #something, nav ul li, inputr, nav ul input:checked ~li label.abrir { display:none; } nav ul input:checked ~li, nav ul li.fixo, li.abrir { display: block; }…
-
0
votes2
answers286
viewsA: Python: How to identify the root of the operating system?
I got the solution, gentlemen. os.path.commonpath(os.get_exec_path()) The association of the above commands will always display the operating system root (OS), for any OS. :D…
-
0
votes2
answers286
viewsQ: Python: How to identify the root of the operating system?
As I identify the root of the operating system (windows: "C: ", No linux: "/"), exclusively through python commands that apply to both systems?
-
0
votes0
answers38
viewsQ: Python3: How to treat relative paths with module os
I’ve got it down: def get_conteudo_file(filename: str, encoding: str="iso8859-1") -> str: filename = os.path.abspath(os.path.join(*filename.split(os.sep))) assert os.path.isfile(filename),…
python-3.xasked britodfbr 688 -
0
votes0
answers94
viewsQ: How to perform unit test with unittest.mock for reading and writing files?
Good Night!!! This time my doubt is about unit tests. Come on. How can I test the section below in unittest.mock environment? def save_html_file(conteudo, filename, encoding='iso8859-1'): assert…
-
0
votes1
answer741
viewsA: Error in pycharm
I found the solution. Follow: On the main menu: Run > Edit Configurations... In the window that opens, on the left select the problematic project... on the right select the subaba(ear)…
-
0
votes1
answer741
viewsQ: Error in pycharm
Good morning, everyone, In "file>Settings>project: ... > project interpreter" the environment has been configured: "/home/Brito/projetos/venv/saj_projects/bin/python" And I’m experiencing…
-
0
votes2
answers217
viewsQ: Default list replacement in regex
People need to turn a string into a list, in a peculiar way. I found in this post what I need to do. But I’m lost on the regex applied. I have numerous string in the following format: ["DECRETO Nº…
-
0
votes1
answer1363
viewsA: import openpyxl / Modulenotfounderror: No module named 'openpyxl'
Activate the virtual desktop and run easy_install: $ source venv/py36/bin/activate $ easy_install openpyxl
-
1
votes0
answers29
viewsQ: Multiple search factors in an html file with variable parameters
Good morning, everyone. Needed to search by the name of the presidents of brazil, in html files. I created a json with the names of the presidents to facilitate. Follows the code: # !/bin/env python…
-
3
votes1
answer84
viewsQ: bs4: How to wrap an incomplete html code?
Hello, I came across incomplete html codes where are missing the tags "html" and "body". Follow the code I implemented: import bs4 content=''' <head> <title> my page </title>…
-
0
votes2
answers6485
viewsA: Python - Moving files to another folder
__author__ = '@britodfbr' import shutil from os import listdir from os.path import isfile, join, basename def move(path_origem, path_destino, ext='zip'): for item in [join(path_origem, f) for f in…
python-3.xanswered britodfbr 688 -
0
votes2
answers1104
viewsA: How to create a virtualenv with a python seaman other than the ones installed?
If your environment is anaconda: Conda create --name meu_amb_py34 python=3.4 Details in http://brito.blog.incolume.com.br/2018/06/anaconda.html…
-
2
votes2
answers280
viewsA: How to move multiple ZIP files at once with Python
I believe this solution meets your need. __author__ = '@britodfbr' import shutil from os import listdir from os.path import isfile, join, basename def move(path_origem, path_destino, ext='zip'): for…
-
0
votes1
answer176
viewsA: string treatment on pandas
I found the reason for the failure in this post https://stackoverflow.com/a/50496822/5132101. Due to a bug in Python 3.5.2 and earlier, the error happens. My environment is a Linux Ubuntu, which…
-
2
votes1
answer176
viewsQ: string treatment on pandas
Good evening Gentlemen, I have the following Dataframe, imported from an xlsx. NUM_LEGISLACAO DSC_URL COD_SITUACAO ... DSC_TIPO num ano 264 89.272/1984 NaN 2.0 ... NORMATIVO 89.272 1984 265…
-
1
votes3
answers56
viewsQ: Mass collection of information from files
I intend to collect ctime, atime, mtime and crtime from a considerable mass of files. I have assembled the following script as a partial solution: sudo debugfs -R 'stat <1055890>'…
-
0
votes1
answer227
viewsQ: Pandas: How to make a Serie fragment in the field (Column) of the Dataframe
I have this excel below: NÚMERO "URL NÚMERO 16571 SICAN" "URL DECRETOS 2011 PRINCIPAL" 1 CCIVIL_03/Atos/decretos/1991/D00001.html CCIVIL_03/decreto/1990-1994/D0001.htm 4…
-
2
votes1
answer806
viewsQ: Pandas: Dataframe information comparison
I have 2 Dataframes imported from CSV CSV1 4616; CCIVIL_03/decreto/2003/D4616.htm 4617; CCIVIL_03/decreto/2003/D4617.htm 4618; CCIVIL_03/decreto/2003/D4618.htm 4619; CCIVIL_03/decreto/2003/D4619.htm…
-
1
votes2
answers91
viewsA: How to create the <!DOCTYPE html> tag in Beautiful Soup (bs4)
Create Doctype with beautifulsoup elements: >>> from bs4 import Doctype >>> tag = Doctype('html') >>> type(tag) <class 'bs4.element.Doctype'> >>> print(tag)…
-
0
votes1
answer25
viewsA: How to add a sheet to a pre-existing xlsx file with pandas?
I’ve reached this point so far. import pandas as pd from openpyxl import load_workbook file = '{}.xlsx'.format(os.path.basename(__file__).split('.')[0]) def data_frame(): return…
-
0
votes3
answers392
viewsA: How to open remote content with python?
Proxy-free: import requests requests.get('/') Proxy: import requests requests.get('/', proxies={'http':'http://10.1.1.1:8080', 'https': 'https://10.1.1.1:8080'}) or import requests proxies_cfg={…
-
1
votes1
answer1784
viewsQ: Pandas: Create multiple columns in Dataframe
I have a spreadsheet with the following information: NUM_LEGISLACAO DSC_URL ... COD_TIPO DSC_TIPO 0 323/1895 NaN ... 2.0 CONCRETO 1 2.269/1896 NaN ... 2.0 CONCRETO 2 2.397/1896 NaN ... 2.0 CONCRETO…
-
0
votes1
answer25
viewsQ: How to add a sheet to a pre-existing xlsx file with pandas?
Follow my attempts. And still unsuccessful. import pandas as pd def data_frame(): return pd.DataFrame([{'link': 'http://brito.blog.incolume.com.br', 'title':'Blog'}{'link':'http://google.com',…
-
0
votes1
answer53
viewsQ: How to proceed with batch execution for python methods
I have the following code below: def exemplo01(): return 'exemplo01' def exemplo02(): return 'exemplo02' def exemplo03(): return 'exemplo03' def run(): #list of <class 'function'> fx = []…
-
5
votes4
answers36247
viewsA: List files from a Python folder
Hello. The package os, offers a range of possibilities. recursive path + file import os def files_path04(path): for p, _, files in os.walk(os.path.abspath(path)): file in files:…
-
2
votes2
answers68
viewsQ: Python: How to turn a method or a class into obsolete?
This time I want to learn about Python package structures, and I need your help again. How to turn a method or a class into obsolete? How to display a message in the interpreter’s Debugger, when a…
-
0
votes2
answers91
viewsQ: How to create the <!DOCTYPE html> tag in Beautiful Soup (bs4)
I wish to create the tag in Beautiful Soup (bs4), and developed the following: from bs4 import Doctype tag = Doctype('html') I did the above excerpt. But it does not create the tag . How to proceed?…
-
1
votes1
answer43
viewsQ: How to change the behavior of an HTML tag
wish to change tag behavior strike and I need your help. In the change I want the tag to assume a behavior according to the view, where in All commitments, url (#), the text will appear gray and…
-
0
votes2
answers78
viewsA: Request url wikipedia by date
In the example below I am using datetime to display only today’s. from bs4 import BeautifulSoup import requests import datetime url = "https://dumps.wikimedia.org/other/pageviews/2018/2018-04/"…
-
2
votes2
answers829
viewsA: How to pick only numbers between parentheses in Python with regular expression
A complement to @wmsouza’s reply. If the unit of measurement is scalar (mg, g, kg, and so on), the regular expression may be changed '((\d+) w+)' as presented in the section below: Resultado =…
-
0
votes1
answer66
viewsQ: Python: Serialization of json namedtuple classes
import json from collection import namedtuple class Employee: def __init__(self, name, age): self.name = name self.age = age def tojson(self): return json.dumps(self.__dict__) Hello guys, I…
-
0
votes3
answers533
viewsA: Difficulty with web scraping
Only Beautifulsoup from bs4 import Beautifulsoup conteudo = ''' <tr bgcolor="FFF8DC"> <td valign="top">25/06/2014 20:37</td> <td valign="top">25/06/2014</td> <td>…