why python 2.7 doesnt pick pyqt4 installed using homebrew

I needed to fix the application before I migrate it to pyqt5,
so I installed pyqt4 using brew:

brew install cartr/qt4/pyqt

now when I tried launching pyqt4 app I still get this error:

Traceback (most recent call last):
  File "./slideshow", line 18, in <module>
    import utils
  File "/Users/ciasto/dev/python/slideShow/python/utils.py", line 4, in <module>
    from PyQt4 import QtGui, QtCore
ImportError: No module named PyQt4

How should I fix this, How can I make pyqt4 installed in the /usr/local/cellar visible to my application.

command line – I’am not able to run python in sublime text. Is there a solution?

bash: python: command not found
(Finished in 0.0s with exit code 127)
(shell_cmd: python -u “/home/hector/.config/sublime-text-3/Packages/User/print(“IAN”).py”)
(dir: /home/hector/.config/sublime-text-3/Packages/User)
(path: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin)

This is what I get when I run a simple program.

python – ¿Cómo extraer un dato concreto dentro de un .txt basado en líneas de Json?

me gustaría extraer dentro del archivo.txt solo los tweets que vienen con la clave ‘text’:

tweets= open ('Tweets.txt')
contenido={}
for line in tweets:
    contenido=json.loads(line)
    print(contenido)

Con éste código no consigo acceder a la clave que quiero y extraerlo en otra variable

python – Decrease exectution time of my program

I have an array with 40000 number (float and /or int) where I need to perform some calculation. To do this I have used nested for loop. But the execution time is really high. Instead of nested for loop if I use list comprehension, the execution time reduce slightly. Here is one sample of my code,

import numpy as np
import time as t

pox1=  np.random.randint(1000, size= 40000)
time = np.arange(40000)

y=np.zeros(len(pox1))
w=np.zeros(len(pox1))

start = t.time()
for num in range (len(time)-1): 
    z= (((pox1(i) - pox1(i-num)) ** 2) for i in range(num, len(pox1)))
    k=np.mean(z)
    y(num)=k

  # for i in range(num, len(pox1)):
  #    z.append((pox1(i) - pox1(i-num)) ** 2)


endtime = (t.time()-start)
  
print(y,endtime)

Now my question is why list comprehension is taking lesser time? And is there any other way to reduce the execution time?

Eu realizei orientação em objetos em Python da forma correta?

Fala pessoal. Eu estou começando a aprender Orientação a Objetos em Python. Não sou um completo iniciante no assunto, no passado estudei orientação a objetos em PHP e brevemente em Java, e notei que POO em Python difere um pouco dessas linguagens. Para praticar, criei algumas classes e tentei aplicar o que aprendi, incluindo Herança e um pouco de Polimorfismo (sobreposição de métodos, apenas), mas não estou confiante de que o fiz da forma correta/ideal. Testei o código e parece que deu tudo certo, mas gostaria de saber da galera que entende mais se algo que eu fiz foi feito de maneira incorreta/ineficiente ou se algo poderia ser melhorado. Desculpem o código grande, mas ele é bem simples e rápido de analisar (essa é minha primeira pergunta aqui então não sei exatamente como funciona, desculpem se fiz algo errado). Abraços

class Animal:
    def __init__(self, peso, idade):
        self.peso = peso
        self.idade = idade

    def locomover(self):
        pass

    def alimentar(self):
        pass

    def som(self):
        pass


class Mamifero(Animal):
    def __init__(self, peso, idade):
        super().__init__(peso, idade)
        self.membros = 4

    def locomover(self):
        print("correr")

    def alimentar(self):
        print("leite materno")


class Reptil(Animal):
    def __init__(self, peso, idade):
        super().__init__(peso, idade)
        self.membros = 4

    def locomover(self):
        print("rastejar")

    def alimentar(self):
        print("pequenos animais")


class Ave(Animal):
    def __init__(self, peso, idade):
        super().__init__(peso, idade)
        self.membros = 4

    def locomover(self):
        print("voar")

    def alimentar(self):
        print("pequenos animais")


class Leao(Mamifero):
    def __init__(self, peso, idade):
        super().__init__(peso, idade)

    def alimentar(self):
        print("caça")

    def som(self):
        print("rugir")


class Morcego(Mamifero):
    def __init__(self, peso, idade):
        super().__init__(peso, idade)

    def locomover(self):
        print("voar")

    def alimentar(self):
        print("sangue")


class Tartaruga(Reptil):
    def __init__(self, peso, idade):
        super().__init__(peso, idade)

    def locomover(self):
        print("nadar")

    def alimentar(self):
        print("algas")


class Serpente(Reptil):
    def __init__(self, peso, idade):
        super().__init__(peso, idade)
        self.membros = 0

    def som(self):
        print("sibilar")


class Cisne(Ave):
    def __init__(self, peso, idade):
        super().__init__(peso, idade)

    def alimentar(self):
        print("sementes")

    def locomover(self):
        print("nadar")


class Abutre(Ave):
    def __init__(self, peso, idade):
        super().__init__(peso, idade)

    def alimentar(self):
        print("comer carcaças")

PS: a ideia da classe Animal é funcionar como uma classe abstrata. Não sei se é adequado classificá-la assim, mas a intenção é que essa classe não seja instanciada (ela possui um construtor explícito, mas não encontrei forma melhor de trabalhar com os atributos peso e idade)

python – Is there a better way to parse this data file?

I have a text data file in SPWLA format; I cannot find a specification for it. It contains physical measurements and/or rock descriptions from wellbore core samples. It’s fairly gross. The example here is substantially simplified:

text = """
30     1
     2001.10     0.00   2.11
40     1   2
     -1002.0000 34.5678
30     1
     2001.90     0.00   1
36     1    1
    Sst.Lt-gry. Pyr.
40     1   2
        18.72400    15.45700
30     1
     2002.90     0.00   2
36     1    1
    Sst.Lt-gry. W-cmt.
"""

This example contains data records for three depths in the wellbore:

  • Record type 30 gives the depth of the following group of records.
  • Record type 36, if present, contains a string in a DSL.
  • Record type 40, if present, contains the data whose fields are listed in another record type.
  • I don’t think there can be more than one ’30’ record for a given depth, and in my solution I assume there cannot.

There are several other record types, but I’ve left them out of this example.

I’ve written a parsing expression grammar (PEG), using Python parsimonious, to describe this format:

from parsimonious import Grammar

grammar = Grammar(
    r"""
    file          = data_blocks+

    data_blocks   = depth_block descr_block? data_block?

    depth_block   = "30" WS "1" WS depth WS NUMBER WS NUMBER WS
    descr_block   = "36" WS "1" WS "1" WS description WS
    data_block    = "40" WS "1" WS record_count WS DATA WS

    record_count  = NUMBER+
    depth         = NUMBER+
    description   = SENTENCE+
    field_name    = SENTENCE+

    WS            = ~r"s*"
    NUMBER        = ~r"(-.0-9)+"
    DATA          = ~r"(- .0-9)+"
    COMPANY       = ~r"(-_A-Z)+"i
    SENTENCE      = ~r"(-., /ÅA-Z)"i
    """
)

And this parses successfully, producing an abstract syntax tree (AST):

ast = grammar.parse(text)

According to the docs, the usual approach now is to subclass the NodeVisitor class in parsimonious to crawl the AST, returning whatever you need from each node’s special method (for example, the visit_description() method determines what gets returned from the description nodes). Here’s my node crawler:

from parsimonious import NodeVisitor

class FileVisitor(NodeVisitor):
    
    def visit_file(self, node, visited_children):
        data = {}
        for record in visited_children:
            data.update(record)
        return data

    def visit_field_block(self, node, visited_children):
        *_, fields = visited_children
        return fields

    def visit_field_row(self, node, visited_children):
        *_, field, _ = node.children
        return field.text.strip()
    
    def visit_data_blocks(self, node, visited_children):
        depth, descr, data = visited_children
        descr = descr(0) if isinstance(descr, list) else ''
        data = data(0) if isinstance(data, list) else ()
        return {depth: {'descr': descr, 'data': data}}
    
    def visit_depth_block(self, node, visited_children):
        _, _, _, _, depth, *_ = node.children
        return float(depth.text)

    def visit_descr_block(self, node, visited_children):
        *_, descr, _ = visited_children
        return descr

    def visit_description(self, node, visited_children):
        return node.text

    def visit_data_block(self, node, visited_children):
        *_, data, _ = visited_children
        return data
    
    def visit_DATA(self, node, visited_children):
        return (float(x) for x in node.text.split())
        
    def generic_visit(self, node, visited_children):
        return visited_children or node

I run it like so:

fv = FileVisitor()
fv.visit(ast)

The result is this dictionary:

{'data': {2001.1: {'descr': '', 'data': (-1002.0, 34.5678)},
  2001.9: {'descr': 'Sst.Lt-gry. Pyr.', 'data': (18.724, 15.457)},
  2002.9: {'descr': 'Sst.Lt-gry. W-cmt.', 'data': ()}}}

Which is what I want, but my question is: is there a more efficient way to write this NodeVisitor? In particular:

  • Can I avoid the data = data(0) if isinstance(data, list) else () business, which I seem to need to deal with the data (and description) node sometimes being empty?
  • Writing things like _, _, _, _, depth, *_ = node.children feels a bit fragile and hard to maintain, which obviates solving the entire problem this way. Am I missing something?

I know I can do all this with string processing or regex, and I’ve done both. I’m interested in using a PEG-based method, because I’m drawn to the idea… but clearly I’m a little out of my depth! I guess I was hoping to be able to focus on maintaining the grammar, but writing that was relatively easy (assuming I’ve done it in a reasonable way!). The hard part was writing this tree crawler thing. So I’m wondering if I just swapped one kind of fragility (chained string methods or lengthy regexes) for another.

Como agregar random items a una lista en python?

Tengo un ejercicio en el cual se me presenta una lista .
Se me pide agregar 10 numeros random a esta usando la funcion randomint()
sin embargo no se como hacer para agregar 10 de estos numeros random a mi lista

import random

my_list = (4,5,734,43,45) 

por ejemplo creo mi variable random asi:

random_number = random.randomint(0,99)

sin embargo no se como podria agregar con un loop 10 numeros random a mi lista.
La salida tiene que ser un nuevo array con 15 items. Intento con append pero no me funciona

Gracias por su ayuda!

python – Error “NoneType” pricesamiento de imagenes

Cuando ejecuto este código, me aparece error:

import cv2

#Carga la imagen
img = cv2.imread('estrella.png')

#Convierte la imagen a escala de grises
imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)

#Determina los contornos
image,contours, hierarchy = cv2.findContours(thresh,1,2)
cnt = contours(0)

#Determina los defectos de convexidad
envoltura = cv2.convexHull(cnt,returnPoints = False)
defectos = cv2.convexityDefects(cnt,envoltura)

#Dibuja la envoltura convexa y los defectos de convexidad
for k in range(defectos.shape(0)):
    i,f,l,d = defectos(k,0)
    inicio= tuple(cnt(i)(0))
    fin= tuple(cnt(f)(0))
    lejos = tuple(cnt(l)(0))
    cv2.line(img,inicio,fin,(0,255,255),2)
    cv2.circle(img,lejos,5,(0,0,255),-1)

#Muestra la imagen final
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

#Guarda la imagen
cv2.imwrite('def_convexidad.png',img)

Error:

AttributeError Traceback (most recent call last)
in
14
15 #Dibujar la envoltura convexa y los defectos de convexidad
—> 16 for k in range(defectos.shape(0)):
17 i,f,l,d = defectos(k,0)
18 inicio= tuple(cnt(i)(0))
AttributeError: ‘NoneType’ object has no attribute ‘shape’

Combinatorics challenge solved it Python

The easiest way to explain this problem is to show these two test cases:

assert solution('ABC') == ('A', 'B', 'C', 'AB', 'AC', 'BC', 'ABC')
assert solution('ABCD') ==  ('A', 'B', 'C', 'D', 'AB', 'AC', 'AD', 'BC', 'BD', 'CD', 'ABC', 'ABD', 'ACD', 'BCD', 'ABCD')

my solution is below:

def subsolution(lst, length):
    return (lst + (x) for x in·
            range(lst(-1)+1, length))

def solution(symbols):
    length = len(symbols)
    result = (((x) for x in range(length)))
    while True:
        subres = ()
        for x in result(-1):
            subres.extend(subsolution(x, length))
        if not subres:
            break
        result.append(subres)
    result = ( item for sublist in result
        for item in sublist
    )
    result = (
        ''.join(symbols(s) for s in el)
        for el in result
    )
    return result

Python: Find exceptions inside a list

Good evening,

I’m having a list with a random amount of integers and/or floats. What I’m trying to achieve is to find the exceptions inside my numbers (hoping to use the right words to explain this). For example:

list = (1, 3, 2, 14, 108, 2, 1, 8, 97, 1, 4, 3, 5)
  • 90 to 99% of my integer values are between 1 and 20
  • sometimes there are values that are much higher, let’s say somewhere around 100 or 1.000 or even more

My problem is, that these values can be different all the time. Maybe the regular range is somewhere between 1.000 to 1.200 and the exceptions are in the range of half a million.

Is there a function to filter out these special numbers?

Thanks and a good evening.

finethen