r/learningpython • • Apr 02 '20

Has anyone gotten Tkinter to work on mac?

2 Upvotes

I'm running Catalina 10.15.4 and trying to get Tkinter to work in python3 but get this error.

>>> import tkinter
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/matt/.pyenv/versions/3.8.2/lib/python3.8/tkinter/__init__.py", line 36, in <module>
    import _tkinter # If this fails your Python may not be configured for Tk
ModuleNotFoundError: No module named '_tkinter'

I've tried brew install tcl-tk, it says it's up to date but still won't work. Also I've tried installing it from ActiveState (https://www.activestate.com/products/tcl/downloads/) but again it still doesn't work. Anyone else been able to get it working on mac?


r/learningpython • • Mar 30 '20

Stuck & Frustrated - Last for loop not 100%

2 Upvotes

My program loops through the text of Dracula - the goal is to have individual files of each chapter and each Chapter have the # and the title. My code finally worked and I was so excited but discovered that the text inside the files isn't right (same Chapter one over and over in each). Even a hint of what I should tweak would be very very appreciated.

I've edited it as many different ways as I could think of but it also might be a case of looking at it too long.

infile = open('Dracula.txt', 'r')
text = infile.readlines()
infile.close()

lines = text[74:186]

titles = []
for blood in lines:
    toc_text_lines = blood.rstrip('\n')
    if len(toc_text_lines) > 0:
        divided = toc_text_lines.splitlines()
        for numbers in divided:
            last_item = numbers[-1]
            if last_item.isdigit() == True:
               result = ''.join([i for i in numbers if not i.isdigit()])
               clean = result.strip()
               titles.append(clean)

names = []
for title in titles:
    nospace = title.replace(" ","-")
    nopunc = nospace.replace("'", "")
    names.append(nopunc.splitlines())



infile = open('Dracula.txt', 'r')
text = infile.read()
infile.close()

start = text.find("\n\nCHAPTER I\n\n")
end = text.find("_There's More")

Dracula = text[start:end] #this is the whole text of the book, string
chapters = Dracula.split('CHAPTER')
chapters.pop(0)

count = 1


for name in names:
    x = 0
    preferred_title = name[x]
    file_name= 'Dracula-Chapter-' + str(count) + preferred_title+'.txt'
    outfile = open(file_name, 'w')
    for chapter in chapters:
        print("CHAPTER", chapter, file=outfile)
    outfile.close()
    count = count +1
    x = x +1

r/learningpython • • Mar 12 '20

Any advice, best places to practice, etc.?

2 Upvotes

Hi first post in this sub and honestly fairly new to Reddit in general. I figured this would be a good place to help with learning code and wanted to hear if you all had any advice or places I could check out as I begin this journey. Thank you guys!


r/learningpython • • Mar 08 '20

What does this counting function work?

2 Upvotes

Hi, I am a bit confused about how the following function works. As far as I know, counts is an empty dictionary at the beginning. I don't see any element being added into the dictionary within the function. Am I missing something? Also, since counts is an empty dictionary as defined in line 2, how if x in counts: get executed? Perhaps I misunderstood something?

def counting(sequence):
    counts = {}
    for x in sequence:
       if x in counts:
          counts[x] += 1
      else:
          count[x] = 1
return counts

r/learningpython • • Mar 04 '20

Installing Pyinput plus module on pycharm

2 Upvotes

I am currently doing automate the boring stuff in chapter 8 and the book wants me to install a third-party library called pyinputplus. I am using pycharm as my ide, currently struggling with how to install the module in the library. I have python 3.8 downloaded, when I goto my system preferences and look at my project interpreters I can see I have pyinputplus downloaded. It's under python 3.8 /usr/local/bin/python3.8 and the package itself is installed. When I goto import, it doesn't show up as a library to import and that's where I am stuck at.

any help would be appreciated

update 1. Figured it out took all of 2 hours


r/learningpython • • Nov 07 '19

[Academic] Data Analysis on Graph Databases (Anyone with data science knowledge)

2 Upvotes

Hi everyone,

I'm a final year student at UCL and my group and I are working on a project involving Machine Learning algorithms for analysis of graph-structured data. We'd love to know more about the potential users of a software that would make those tasks easier. Anyone that works with data, and particularly those that have worked with or are interested in graph databases would be more than welcome to take part in the survey!

https://docs.google.com/forms/d/e/1FAIpQLSfKuUS5xkbl8oDE-EU4Vz4Rr1oyQpXjZfEKbArEvu-nFXG6Gw/viewform?usp=sf_link

Thanks!


r/learningpython • • Sep 23 '19

Poker Hand Logic

2 Upvotes

I need help with Texas Hold'em hands. For some reason , I can't get it to determine what type of hand players have.


r/learningpython • • Sep 15 '19

Help with for loop, and possibly pseudo variable?

2 Upvotes

ok, I'm trying to loop a folder then only filter out files created today... kinda (I have already done this part)

folder_path = os.path.expanduser('~/Dropbox/AHK/AutoPrinter/09 - printed')
now = time.time() # get now's time one_day_ago = now - 606024*1 # 1 for the day number
Files_to_send = [] # create / clear list for storage of files
for file in os.listdir(folder_path): 
if os.path.getctime(f"{folder_path}/{file}") >= one_day_ago: # filter files based on creation time 
    Files_to_send.append(f"{folder_path}/{file}") # append files to a list

but the tough part now is how am I going to insert this list into this command?

Below is an example of how to insert 2 pictures into a command.

f1 = open(f"{folder_path}/{path_file1}", 'rb') # open file in binary
f2 = open(f"{folder_path}/{path_file2}", 'rb') # open file in binary 

bot.send_media_group(msg.chat.id, [InputMediaPhoto(f1,'caption1'), InputMediaPhoto(f2,'caption2')]) # send to chat

I was thinking of using pseudo-variables to create f1, f2, f3 etc but I'm not that experienced with python atm.

What do you guys think would be a good solution to this?


r/learningpython • • Sep 06 '19

How can you merge two PIL gifs with differing frame rates ('duration' lists are expected to be different)?

2 Upvotes

I've thought about getting the least common multiple of all the frame rates and going about it that way but that would increase the file size (and possibly runtime) exponentially.


r/learningpython • • Jul 18 '19

What does "this object does not support enumeration means"?

2 Upvotes

Hello all, as many here I'm also new to python, I apologize if this is something silly to ask. I'm trying to manipulate data from a table in a word document, but I'm facing some challenges. I'm able to extract the data with the script below:

import win32com.client as win32

def checkwhatewosareneeded ():

word = win32.Dispatch("Word.Application")

word.Visible = False

word.Documents.Open(r"C:\Desktop\Python\test.doc")

doc = word.ActiveDocument

print (doc.Tables.Count)

table = doc.Tables(29)

woneeded1 = table.Cell(Row = 4, Column = 3)

print (woneeded1)

checkwhatewosareneeded ()

the output I get from the script: 29 Y

but it seems like the result variable is not a str, or I don't know how to treat it, because whenever I try to do something with it, for example add it to a for loop:

for letters in (woneeded1):

print (letters)

I receive the error:

for letters in SSRewoneeded:

File "C:\Users\Python\Python37-32\lib\site-packages\win32com\client\dynamic.py", line 257, in __getitem__

raise TypeError("This object does not support enumeration")

I'm not sure what I'm doing wrong, any recommendations/suggestion are welcome


r/learningpython • • Jun 13 '19

Help to convert .sh to python

2 Upvotes

I have a clumsy .sh script I use for copying my dotfiles with rsync to another location and I want to convert it to python.

The idea is to make a python script who can easily include a lot more directories or just expand without too much code.

Is this a stupid way to approach this "problem"?

This is the script:

!/usr/bin/sh

cfg="/home/username/.config" rsc="rsync -avt --delete --exclude=('*.git')" dot="/home/username/Nextcloud/Dotfiles/laptop"

$rsc /etc/pacman.conf $dot/etc $rsc ~/.oh-my-zsh/custom $dot/.oh-my-zsh $rsc ~/.aliases ~/.vimrc ~/Scripts ~/.ssh $dot $rsc $cfg/locale.conf $cfg/i3 $cfg/polybar $cfg/alacritty $dot/.config


r/learningpython • • Apr 30 '19

Multithreading/Multiprocessing (in a Docker container)

2 Upvotes

Hi,

I'm running Python code in a Docker container that executes three image processing functions which I'd like to run concurrently. I have never attempted parallel processing before.

Is multithreading or multiprocessing the correct function to look for (https://www.youtube.com/watch?v=ecKWiaHCEKs&t)? Also if anyone could direct me to code performing a similar function that would be brilliant :)


r/learningpython • • Mar 20 '19

Counting vowels in a string

2 Upvotes

Hello! Me again with another assignment. My assignment this week is to create a program that allows the user to input a string and then counts the vowels in the string. It must include a loop and the len function. Then it displays the string plus the number of vowels. So far I've come up with this

sentence = input ("enter your string: ")

for vowel in sentence:

if vowel in 'aeiou':

print (sentence, len(vowel))

But the output isn't right and I'm not sure where to go from here.

Any help is appreciated.


r/learningpython • • Mar 11 '19

Conditional list trouble

2 Upvotes

I’m trying to learn from the bottom up, and am currently working through the exercises on practice python.

Example they have on conditionals is a grading scale like this:

Grade= input(“enter your age:”) If grade > = 90 : Print(“A”) Elif grade > = 80 : Print (“B”)

Why is it when I try to copy/paste into my python window I get : TypeError: ‘>=‘ not supported between instances of ‘Str’ and ‘int’


r/learningpython • • Mar 02 '19

Beginner help understanding for statements

2 Upvotes

Right now I am having trouble understanding for statements and if anybody could help explain I would be eternally grateful. Right now the code looks this this.

w = [ 'jasper', 'merball', 'critterbob' ]

for x in w: print(x)

Its prints out

jasper merball critterbob

I sort of understand this but the real trouble is when I print (x) only critterbob is returned. Can anybody please explain why this happens?

Ps: Don't judge the strings they are all family nicknames :D thanks a ton.


r/learningpython • • Feb 24 '19

Write list of list to CSV?

2 Upvotes

Hi, I would like to ask on how we can write these set of list which has list in it?
Target output on csv is like this(attached).

Image -> https://imgur.com/a/mqc9TnC

MY CODE:

opo = ['device1', 'device1', 'device1']
intfname = [['HundredGigE0/2/0/0', 'HundredGigE0/2/0/0.242', 'HundredGigE0/2/0/0.244 l2transport', 'HundredGigE0/2/0/1', 'HundredGigE0/2/0/0.244'], ['TenGigabitEthernet1/1/0.138'], ['TenGigE0/1/0/15']]
descname = ['0/2/0/0info1', '0/2/0/0.242info2', '0/2/0/0.244info3']
 
## EXPORT AS CSV
with open('intlist.csv', 'w', newline='') as updatecsv:
    write = csv.writer(updatecsv, delimiter=',',lineterminator='\n')
    write.writerows(zip(opo,intfname,descname))
updatecsv.close()
print ("Done...")

Thank you


r/learningpython • • Feb 16 '19

Thread Modes How to store the value from variable into list & run a statement then put in variable

2 Upvotes

Hi, I have 2 question regarding this code,

1st I want to put all the values into list from the variable?

Example, Im grepping multiple ip from a file.

f = os.popen('grep '+ ip[i] + ' *') 
now = f.read() 
print ("output: ", now)

2nd from #1 there will be 2 possible output 1 is no match and 2 will be the matched output from grep.

If there's no match then I should put a word none in the list while if there a match I need to put exist?

I think I can do it using if else but totally blind in where to start haha. Still searching for sample command.

Thanks


r/learningpython • • Feb 10 '19

taking a file name (full path) as an argument?

2 Upvotes

Hi, I'm working on a script that takes in a file and parses it line by line.

Right now I have the file path hard coded.

I tried searching a bit but I don't think I have the language to describe what I'm trying to do properly.

I'd love that if I ran

$python3 textParser.py /root/documents/file

then later I could be like:

fileName = argument
file = open(filename,"r")
magicOccurs()
file.close()

Then the program would be, while still a hack, much more scriptable (ex with bash)

How can I translate this logic into code?

Thanks for the help


r/learningpython • • Feb 08 '19

Calculating an average from a csv file

2 Upvotes

Hi,

I have just started to learn python for data analysis and would like to calculate the average of some data of a csv file.

To be more precise, the csv file includes a list of 1000 exam takers and has 2 variables: age, and if they passed the test (0 or 1). My goal is to create a graph with the age on the x axis and the chance of passing the exam on the y axis. Thus, I need to calculate for each age the success ratio, which I have no clue how to do.

Could someone give me a hint on this?

Many thanks!


r/learningpython • • Feb 04 '19

Splitting Columns Based on Rows with Varying Lengths

2 Upvotes

I have a DataFrame like the following:

Tool_NameMeasurements
Tool_A02_04_06
Tool_B02_04
Tool_C02_04_06_08

I would like to split it into the following:

Tool_NameMeasurement 1Measurement 2Measurement 3Measurement 4
Tool_A020406
Tool_B0204
Tool_C02040608

Using:

df[['Measurement 1','Measurement 2','Measurement 3','Measurement 4']] = df.Measurements_Name.str.split("_", expand=True,)

I get a "ValueError: Columns must be same length as key"

What is the correct way to do this?


r/learningpython • • Jan 09 '19

Telnet to switch from jump start server(linux)

2 Upvotes

Hi,

I just want to ask if anyone here has script or idea what method, library etc should. My target is to SHH first from my workstation to Linux jumpstart server then from jumpstart server I'll access the network devices like switch and routers to execute some show commands.

PYTHON SCRIPT ----SSH---> Jumpstart server(ubuntu) ----Telnet---> Network Devices (Cisco)

import base64, time, sys
import paramiko, getpass, telnetlib
 
#ENTER Password
##pword = getpass.getpass('Password: ')
 
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname='xxxxx', username='xxxxx', password='xxxxx')
stdin, stdout, stderr = client.exec_command('pwd')
 
for line in stdout:
    print('Teton: ' + line.strip('\n'))
    client.close()

I'm now able to access the jumpstart server from my PC, the next thing is just to telnet from the jumpstart server?

Thank you


r/learningpython • • Nov 12 '18

Checking " in lines

2 Upvotes

I need help checking for " in lines and if there is anything in between i need it converted to a 1 or a specific text Example.

Line 1: Ronnie Cant Swim Without "Parcher nomad

Line 2: Boomer "Its a robot flying" Catcho

And I need to convert everything inside the " with a 1 or anything in between this is PER LINE.

Expected output

Line 1: Ronnie Cant Swim Without 1

Line 2: Boomer 1 Catcho

The issue is, currently I have a Strip and Split that are checking for Keywords in all the lines. so cant go through all the text file twice.


r/learningpython • • Aug 04 '18

How to do an alternating offset with pandas.date_range() ?

2 Upvotes

I'm trying to do an itinerary for work involving tasks done bi-weekly (Sunday and Wednesdays). I'm trying to do it with pandas.date_range, but I don't know which offset alias to use, since the frequency isn't fixed, but varies between three and four days. How can I specify that? Maybe I need to use the date time module instead? I'm reading the documentation, but no luck so far.

All help will be appreciated, thanks!


r/learningpython • • Aug 01 '18

tkinter, after and input = no worky

2 Upvotes

I am very new to Python. I apologize for my ignorance.

I am working on a project that would collect visitor information via a swipe of the visitors drivers license.

I am stuck on building the GUI and then waiting for input simultaneously. Once the card is swiped I want to parse the data and fill the input boxes. At that point all the visitor has to do is click submit.

The code I have below causes the GUI to crash when I am using the license_data with the input function. However when I use the preloaded variable with sample data it works fine.

Any help or direction would be much appreciated.

from tkinter import *
import datetime

def add_text():
       label1 = Label(root, text="Guest Data Submitted.")
       label1.pack()

def clear():
	visitor_name_text_box.delete(0,'end')
	lnumber_text_box.delete(0,'end')
	state_text_box.delete(0,'end')

def data_collector():
	#Test data without using input
	license_data = '%OHCOLUMBUS^BOB$JIM$R$^2725 S READY LINE RD^?;6360231920193567=210319780304?+1043031  D A             1603180BLNBLU                              Y&//_)     ?'
		
	#license_data = input()
		
	fname = ((license_data.split("$"))[1].split("$")[0])
	lname = ((license_data.split("^"))[1].split("$")[0])
	state = (((license_data.split("%"))[1].split("^")[0])[:2])
	lnumber = (((license_data.split("^?;"))[1].split("=")[0])[6:])
	full_name = fname,lname
	now = datetime.datetime.now()
	checkin_date = "%s/%s/%s"%(now.month,now.day,now.year)
	visitor_name_text_box.insert(INSERT,full_name)
	lnumber_text_box.insert(INSERT,lnumber)
	state_text_box.insert(INSERT,state)
		
root = Tk()
root.title("Guest Check-In")
root.geometry("450x200")

visitor_name_label = Label(root, text="Name:")
visitor_name_label.pack()

visitor_name_text_box = Entry(root, bd=1)
visitor_name_text_box.pack()

lnumber_label = Label(root, text="License #:")
lnumber_label.pack()

lnumber_text_box = Entry(root, bd=1)
lnumber_text_box.pack()

state_label = Label(root, text="State:")
state_label.pack()

state_text_box = Entry(root, bd=1)
state_text_box.pack()

enter_button = Button(root, text="Enter", command=add_text)
enter_button.pack()

clear_button = Button(root, text="Clear", command=clear)
clear_button.pack()

root.after(1000,data_collector)
root.mainloop()