r/learningpython • • Aug 25 '22

Extra Delimiters in csv files

1 Upvotes

I have to read a csv file with delimiter = “;”. The problem is that there is an extra delimiter inside values of first column, so pd.read_csv returns two columns instead of one. Please help me out thanks


r/learningpython • • Aug 17 '22

windows NT app?

1 Upvotes

Hi there, how can I write the python coding in windows 10 and package it as a windows NT application (exe) using auto-py-to-exe? Need special version of Python? can i still use tkinter to design the user interface in it? Many thanks!


r/learningpython • • Aug 11 '22

Losing rows when merging dataframes

1 Upvotes

Hi there,

I have two dataframes with the length of 29981. but when I merge them like this:

new_df = new_data_scaled.merge(data_prep, left_index=True, right_index=True)

the length of the new_df becomes 29963.

How can I improve it? Thanks in advance


r/learningpython • • Aug 10 '22

Root finding in case of multivariable functions

1 Upvotes

Hello, everyone,

I am trying to find the roots of a function which is basically a mapping from R12x1 to R 6x3. I am using fsolve to find the roots but it throws an error saying :

fsolve: there is a mismatch between the input and output shape of the 'func' argument 'f'.Shape should be (12,) but it is (6,3).

Any suggestion would be of great help.

Thank you.


r/learningpython • • Aug 06 '22

Custom ContextManager

1 Upvotes

Hi all,

I found an exercise asking to write a class behaving as a custom ContextManager (and use it with the "with" statement).

I do not know from where to start.

I only know that I've to write some methods:

def __init__(self, *args, **kwargs):
pass

def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass

where I can find some good tutorial?

the example said ssomething like:

value = 0

with MyContextManager(argument):

value = function(a, b, c)

assert value.x == 12

assert value.name = "myname"


r/learningpython • • Aug 05 '22

Python won't run

Post image
1 Upvotes

So I've been learning python for the past few weeks. So as you can see in the photo python should run the program going form 1 to 9 but when I execute the program it gives me a blank/empty output. Does anyone know what's the problem here?


r/learningpython • • Jul 28 '22

Learning Python as a second language.

1 Upvotes

Learning Python as a second language.

Currently I am learning Python as a second programming language and I am having some difficulties.

I understand syntax, setting up functions, etc.

The problem I am having is that my primary language I have been developing automation instrumentation and control applications in is LabVIEW.

What is tripping me up in learning Python are some of the concepts that are native to LabVIEW parallel execution, queues, actors, asynchronous processes, etc.

I know it can be done in Python but after doing all my programming visually for the last 10+ years I am having trouble visualizing doing the same thing in a text based programming paradigm.

LabVIEW does a lot of the heavy lifting. Y setting up variables working with me or, etc. I realize that must be done “by hand” I’m Python and I am getting adept at that.

It is the multi process setup and execution that is throwing me for a loop (no pun intended).

Does anyone have any resources, suggestions, etc. on how I can retrain my brain to think in this manner with Python.

Everything I do in LabVIEW is object oriented so that I have no problem with.

TIA

-Steven


r/learningpython • • Jul 16 '22

tKinter scroll bar adjustment to the list box

1 Upvotes

Hi All, I am new to tKinter package. I am trying to fix/attach scroll bar to the listbox however nothing works, If I put functionality, the scroll bar works but then it doesnt size up to the entire list box window and doesnt even attach to it.

Any help will be really appreciated. below is the code for the tKinter window.

from tkinter import *

app = Tk()

label1_text = StringVar() part_label = Label(app, bg='#dfe3ee', text='Check1', font=('bold',12), pady=10, padx=20) part_label.grid(row=0, column=0, sticky=W) label1_entry = Entry(app, textvariable=label1_text) label1_entry.grid(row=0, column=1)

label2_text = StringVar() part_label = Label(app, bg='#dfe3ee', text='Check1', font=('bold', 12), pady=7, padx=20) part_label.grid(row=1, column=0, sticky=W) label2_entry = Entry(app, textvariable=label2_text) label2_entry.grid(row=1, column=1)

label3_text = StringVar() part_label = Label(app, bg='#dfe3ee', text='Check3', font=('bold', 12), pady=20) part_label.grid(row=0, column=2) label3_entry = Entry(app, textvariable=label3_text) label3_entry.grid(row=0, column=3)

label4 = StringVar() part_label = Label(app, bg='#dfe3ee', text='check4', font=('bold', 12), pady=7) part_label.grid(row=1, column=2) label4_entry = Entry(app, textvariable=label4) label4_entry.grid(row=1, column=3)

B1_btn = Button(app, bg='#cd8de5', text='Button1',font=('bold', 11), width=12) B1_btn.grid(row=3, column=1, padx=0, pady=5)

B2_btn = Button(app, bg='#cd8de5', text='Button2',font=('bold', 11), width=12 ) B2_btn.grid(row=4, column=1, padx=0, pady=5)

B3_btn = Button(app, bg='#d5a6e6', text='close',font=('bold', 11), width=12) B3_btn.grid(row=50, column=2, sticky='E')

output_list = Listbox(app, height=20, width=100, border=5) output_list.grid(row=20, column=0, columnspan=3, rowspan=6, pady=20, padx=20)

scrollbar = Scrollbar(app) scrollbar.grid(row=20, column =3, rowspan=5, sticky=(N+S))

output_list.configure(yscrollcommand=scrollbar.set) scrollbar.configure(command=output_list.yview)

app.title('Test Tool') app.geometry('900x900') app.configure(bg='#dfe3ee')

app.mainloop()


r/learningpython • • Jun 06 '22

cant figure out how to divide a datetime object by an int

1 Upvotes

my issue is, I cant seem to divide a datetime object by an int.

looking at the documentation I cant figure out why it isn't working.

I get the error: unsupported operand type(s) for /: 'datetime.time' and 'int'

import datetime

from datetime import datetime, timedelta, timezone, date
time = datetime.strptime("04:23:40", "%H:%M:%S")
print(time)
print(time.time())
time_div = time.time() / 2
print(time_div)

Any help would be greatly appreciated.

I did see a method that splits the time down into second then performs the division on the number of seconds, but wondering if there is a better way?


r/learningpython • • Apr 05 '22

Course Recommendation

1 Upvotes

Hi everyone,

I am interested in learning python for web-scraping, interacting with APIs, and a bit of data analysis and visualization. I am considering getting a subscription to DataCamp, but am interested in hearing if there are other recommendations

Note: while I'm tech-savvy, I do not have any background in coding, beyond the few youtube videos I've watched on coding in python.


r/learningpython • • Feb 21 '22

Can't click element after scrolling in Instagram following window

1 Upvotes

I am trying to click the first element that loads after scrolling in an Instagram following window but it will not let me. Here's what I have so far:

from time import sleep
from selenium import webdriver

browser = webdriver.Firefox(executable_path = '/usr/local/bin/geckodriver')
browser.implicitly_wait(5)

browser.get('https://www.instagram.com/')

sleep(2)

username_input = browser.find_element_by_css_selector("input[name='username']")
password_input = browser.find_element_by_css_selector("input[name='password']")

username_input.send_keys("Enter Username Here")
password_input.send_keys("Enter Password Here")

login_button = browser.find_element_by_xpath("//button[@type='submit']")
login_button.click()

sleep(5)

browser.find_element_by_xpath('/html/body/div[1]/section/main/div/div/div/section/div/button').click()

sleep(2)

browser.find_element_by_css_selector('button.aOOlW:nth-child(2)').click()

browser.get('https://www.instagram.com/instagram/')

sleep(2)

browser.find_element_by_css_selector('li.Y8-fY:nth-child(3) > a:nth-child(1)').click()

sleep(2)

follower_number =int( browser.find_elements_by_xpath('//span [@class="g47SY "]')[2].text)
i=0

sleep(5)

while(i<follower_number):
    element = browser.find_elements_by_xpath("//div[@role='dialog']//ul//li")
    browser.execute_script("arguments[0].scrollIntoView(true);",element[i])
    i=i+1

browser.find_element_by_xpath('/html/body/div[4]/div/div/div/div[3]/ul/div/li[12]/div/div[1]/div[2]/div[1]/span/a/span').click()

Here's the error I'm getting:

 browser.execute_script("arguments[0].scrollIntoView(true);",element[i])
IndexError: list index out of range

r/learningpython • • Feb 20 '22

What's wrong here?

1 Upvotes

Hi! I'm new to Python and started learning it on my own with an app from Google Store. This error pops up when I click Run > Run Module. Any idea what I should do? Please explain as simply as possible :)

Edit: This shows up when I delete the 1st two lines:


r/learningpython • • Feb 08 '22

Pathlib vs sqlite3

1 Upvotes

I know it's a strange title let me explain.

The idea is to make a program that will use the information from work orders to select the a cut file that goes with it.

We are talking about 10 to 100 work orders each day to combine 10k+ saved cut files.

My question is, is it better for each word order to search with pathlib with filters for each different jobs or to store the files data in a small sqllite3 database and make queries?


r/learningpython • • Jan 20 '22

Problem when importing functions, all the code runs

1 Upvotes

Hi guys,

I was watching a lesson on how to import functions from a different file, and I replicated the logic on two files:

-moduliPackages.py : it's the file where I import and use functions,

-functions.py: is the file where I have defined the functions

In moduliPackages I am using the statement 'from functions import *', and after that I use print_time(), that is one of the functions imported.

The problem is that when I run moduliPackages it runs all the code that I have written in functions.py (so stuff like print statements ecc).

Any idea what I am doing wrong?

functions.py:

from datetime import datetime
print('Inizio lezione')
def print_time():
    print('task completed')
    print(datetime.now())

def print_task(task_name):
    print(task_name)
    print(datetime.now())

first_name= 'Joe' #input('Inserisci il tuo nome: ')
last_name= 'Jonetti' #input('Inserisci il tuo cognome: ')
first_initial= first_name[0:1]
last_initial= last_name[0:1]
print('the letters are: '+ first_initial + last_initial)

moduliPackages:

from functions import *
print_time()
print_task('test')

r/learningpython • • Jan 15 '22

Should I instantiate 4 Wheel classes inside of a Car class, or keep them separate?

1 Upvotes

I know HOW to do this, but which is considered a BEST PRACTICE?

  1. Instantiate 4 Wheel classes and 1 Car class and use them separately?

  2. Instantiate a Car class, which has 4 wheel properties, each of which instantiates a Wheel class?

  3. Or should I just put everything in the Car class and not even have a Wheel class?


r/learningpython • • Dec 10 '21

Useful clips about Ecommerce business

Thumbnail
youtube.com
1 Upvotes

r/learningpython • • Nov 29 '21

code loading very slowly, how to optimize?

1 Upvotes

Hi there, I am trying to remove stopwords from my training data. The problem is that since the data is very big, the code is very slow. Is there any way to optimize it? Thank you in advance!

from nltk.corpus import stopwords
def stopwords_remove(data):
    stopwords_removed = []
    for parts in data:
        #print(parts[0])
        for word in parts[0]:
            #print(word)
            if word not in stopwords.words():
                #print(word)
                stopwords_removed.append(word)
    #print(stopwords_removed)
    return stopwords_removed
stopwords_remove(train_data)

r/learningpython • • Nov 16 '21

Printing Dictionary to .json file not working

1 Upvotes

So, I have a simple problem:

I am creating a simple database system for entirely personal use as a small project to better understand python and programming in general, I am storing objects as dictionaries containing their places, where they are stored within the place and the current status as a dictionary like so:

def StoreSomething():
Object = input("Object: ")
Place = input("Place: ")
Storage = input("Storage: ")
Status = input("Status: ")
n = 0
while Object in Stuff:
n = n + 1
Object = Object + str(n)
Stuff[Object] = {"Place": Place, "Storage": Storage, "Status": Status}
Menu()

This is then stored in the larger dictionary called "Stuff"(I am bad at variable naming).

I wish to save the Stuff dictionary in it's entirity to a JSON file for later use, I have tried almost every single permutation of:

def Save():
Data = Stuff
json.dump(Data, file, indent = 1)
Menu()

None have yet even been able to produce an empty file, no matter if I opened the file early on in the program or if I had opened it only for the saving function. In test runs this has worked however with:

import json

file = open("test.json", "w")
for i in range(0,500):
iDict = {i : i}
print(iDict)
json.dump(iDict, file, indent = 1)

However I cannot see the issue with my first iteration compared to my test program.

Any ideas?


r/learningpython • • Nov 07 '21

Hello, i recently learned about modules. and i created a calculator with modules. (Gerekli_Moduller) contains necessary functions like multiplaction etc. (Hesap Makinesi) is the place where i used these modules. But I didnt made that txt (pycache) file. What is it?

Post image
1 Upvotes

r/learningpython • • Oct 12 '21

pls help me understand

1 Upvotes

r/learningpython • • Jul 25 '21

Please help me improve this simple text expander

1 Upvotes

I'm trying to figure out the best way to create a simple text expander using Python. Do you have any suggestions for me?

I'm running Linux (Lubuntu 20.04 LTS). I am only looking for a solution that works on Linux. By the way, as an aside, I presume my solution would work on Macintosh OS as well. As for Windows, I'm not sure.

I've been using AutoKey on Linux (which is different than, and distinct, from the similarly named AutoHotKey which runs on Windows) for about 6 or 7 years. It works pretty well but it crashes sometimes and is no longer being actively developed.

Essentially I use AutoKey as a text expander. For example, if I type .tflmk then AutoKey will replace .tflmk with Thanks for letting me know.

I wanted a simpler, more reliable solution that AutoKey that would not require me to install an application that might become essentially orphaned.

After some research I found that by adding the following lines...

 alias paste-script-1="nohup python3 '~/home/script-1.py' --option& exit"
 alias paste-script-2="nohup python3 '~/home/script-2.py' --option& exit"
 alias paste-script-3="nohup python3 '~/home/script-3.py' --option& exit"

to

.bashrc

I could run Python scripts from a terminal that would paste into, say, a text document I was working on or a Gmail I was composing, if the Python scripts contained the following information...

import pyautogui,pyperclip

x = '''I will get back to you later today.'''
pyperclip.copy(x)
pyperclip.paste()
pyautogui.hotkey('ctrl', 'v')  # ctrl-v pastes.

which I could trigger by typing .iwgbtylt into a terminal if the following line were in my .bashrc file...

 alias .iwgbtylt ="nohup python3 '~/home/IWillGetBack....py' --option& exit"

and, of course, if I had created the file /home/IWillGetBack....py.

I posted this question—How can I send a string from script_1 to script_2?—because it seemed better to me to segregate the each of my text expanders from a "main script" in case I wanted to make changes to the main script.

I expect I will end up with several hundred "text expander snippets" that are located in half a dozen or so sub-directories under a folder such as ~/home/my_text_expanders.


r/learningpython • • Jun 30 '21

Taking Your Scripts Run Speed From 0 To 60!!!!!!! | Stock Analysis Tool

1 Upvotes

Hey everyone, everyone at one point has created a script that they think is way too slow. Join me and learn how to make your script run from 0 to 60 in seconds with one simple python script. What are you waiting for click the link down below!!!!!!!!!!!!!!!!!!!!!!!!!!!!

https://www.youtube.com/watch?v=gZhZrwG4D3I


r/learningpython • • Jun 28 '21

How to BeautifulSoup for <b title=""

1 Upvotes

How do I find <b title=""

The employee Sam S. is employee id 1234 that works at McDonalds.

I am not interested in all title's in the page, I am only interested in the div employee section

I would like to get the employee_number, store_number, and employee_name.

However, as it stands aa22 is empty, what am I doing wrong?

soup = BeautifulSoup(buffer, 'html.parser')

    # <div id="employee">
    # <h4><b title="1234">McDonalds #5678</b>Sam S.</h4>

    aa00 = soup.findAll("div", {"id": "employee"})
    for aa11 in aa00:
        aa22 = aa11.findAll("b", {"title" : lambda L: L and L.startswith('title')})
        for aa23 in aa22:
            str_ = aa23.text.replace('\n','')
            print(str_)

            employee_number =
            store_number =
            employee_name =

r/learningpython • • Jun 25 '21

Allocating data randomly using pandas

1 Upvotes

Hi,

I have a list of 10,000 names and a list of 200 subjects, i want to randomly assign the subjects to the students in such a way that each students get 4 to 5 subjects and each subject is assigned to 50 students...pls guide how can it be done using pandas.


r/learningpython • • Jun 11 '21

How do I convert a bunch of leaf-nodes into a sub-graph and generate a DOT file for graphviz?

1 Upvotes

Libreoffice has a whole bunch of class-paths like so: com.sun.star.sheet. It's so huge that I'll be scrolling horizontally forever if I use the typical way of adding nodes to Graphviz and then doing dot.render(). (you can look at their classtree here https://pastebin.com/Z8kHEe0R)

I need to merge the leaf-nodes into a sub-graph and grow that vertically and Graphviz allows such things using rankdir=TB Which means that I need to locate all nodes with leaves >10 and sub-graph those leaves/node.

Can this be done using Graphviz (unlikely it seems more towards plotting DOT files) which means I tried using treelib but I can't find a method to subgraph on condition..

Any solution?? (currently I can generate a console tree using treelib.show() similar to command line tree but I need to grow the graph Top-->Down for printing on A4 and overall looking at)

Libreoffice Class Tree from treelib is here https://pastebin.com/Z8kHEe0R I need to present that clearly.

├── sheet
        │   ├── AddIn
        │   ├── Border
        │   ├── CellAnnotation
        │   ├── CellAnnotations
        │   ├── CellAnnotationsEnumeration
        │   ├── CellAreaLink
        │   ├── CellDeleteMode
        │   ├── CellFlags
        │   │   ├── ANNOTATION
        │   │   ├── FORMULA
        │   │   ├── OBJECTS
        │   │   └── STRING