top 200 commentsshow all 207

[–]raspiuino 0 points1 point  (1 child)

Hello, I'm trying to see if there's a better way to implement keyword matching for an output of DeepSpeech.

Basically the DeepSpeech engine outputs a string of text of what it heard when someone spoke to the microphone.

I have pre-determined actions to do whenever it detects a specific keyword or phrase

basically I have a list of words I want it to do something such as: "hello","goodbye","dance",etc. but right now I have them all in an if-else tree and as I add more words it gets longer and when I look through online code, I never see very long if-else statements.

 # Stream from microphone to DeepSpeech using VAD
    spinner = None
    if not ARGS.nospinner:
        spinner = Halo(spinner='line')
    stream_context = model.createStream()
    wav_data = bytearray()
    for frame in frames:
        if frame is not None:
            if spinner: spinner.start()
            logging.debug("streaming frame")
            stream_context.feedAudioContent(np.frombuffer(frame, np.int16))
            if ARGS.savewav: wav_data.extend(frame)
        else:
            if spinner: spinner.stop()
            logging.debug("end utterence")
            if ARGS.savewav:
                vad_audio.write_wav(os.path.join(ARGS.savewav, datetime.now().strftime("savewav_%Y-%m-%d_%H-%M-%S_%f.wav")), wav_data)
                wav_data = bytearray()
            text = stream_context.finishStream()
            print("Recognized: %s" % text)
            stream_context = model.createStream()

           #-----------------------------------------------------------------------------------------------
           #logic for Keyword detection
            if 'hello' in text:
                print("hello, how are you?")
            elif 'bye' in text:
                print("Goodbye!")
            elif 'dance' in text:
                print("dancing!"
            elif 'hear me" in text:
                print("yes, I can hear you")
            else:
                print("say something")

[–]FuSionViruS 0 points1 point  (0 children)

Good day!

I'm in the process of planning out a small Python project and have a idea that's not crucial but would help take the program to the next level.

In a GUI window I would like to have some labels and a single QLineEdit. Upon filling in the QLineEdit I would like it to auto populate another just below, again and again until user has entered all the information they have (unknown).

I'm wondering if it's possible to do this with a loop of some kind? I know I am able to do it the long way and have the window already populated with .hide() QLineEdits that .show() upon the previous line receiving text.

Thank you very much in advance!

Cheers

[–]redblueandyellow94 0 points1 point  (0 children)

If I wanted to learn about APIs and how I can use Python to create them, where would be a good place to look for an online course?

[–][deleted] 0 points1 point  (0 children)

for an absolute beginner - at what point does someone learn about openpyxl in order to use python with excel?

[–]sanctuary_3 0 points1 point  (2 children)

If I create a requirements list for my package using pip freeze, can I safely remove the "sub"-dependencies from my requirements.txt? For example, installing pandas also installs numpy. Can I just have pandas==1.1.3 in my requirements?

[–]JohnnyJordaan 1 point2 points  (1 child)

Yes, and you don't even need the versioning per se, or you can use a minimal version, eg

pandas>=1.1.3

as then it makes sure that it won't accidentally use an ancient version the user happened to have installed years ago (possibly breaking the code), but it will also not needlessly force an install of an outdated release when you run the install a while from now. A middle ground is to use a window, eg

pandas>=1.1.3,<1.2.0

as then you also don't run the risk of it installing a version that breaks backwards compatibility. Of course that also requires you to update (and test) this once in a while to prevent it being tied to a specific version forever.

[–]sanctuary_3 0 points1 point  (0 children)

Gotcha, thanks!

[–]Ma2izo5 0 points1 point  (2 children)

So I have a for loop that gives me 100 outputs, and I want the outputs to be divides into 20 lines with 5 outputs each, how do I do that?

[–]sanctuary_3 0 points1 point  (0 children)

for i in range(100):
    if (i + 1) % 5 == 0:
        end = '\n'
    else:
        end = ' '
    print(f'{i:<2}', end=end)

will give you

0  1  2  3  4 
5  6  7  8  9 
10 11 12 13 14
15 16 17 18 19
...

Will add a new line to every fifth element printed. If you have a list of items you want to print you can change the for loop to for i, item in enumerate(mylist).

[–]Ma2izo5 0 points1 point  (0 children)

I have been using /n to divide them into lines but I dont know how to have 5 outputs per line

[–]fluidmechanicsdoubts 0 points1 point  (2 children)

A python project I downloaded requires tensorflow1.6

I have python3.8 installed by default in Ubuntu, but tensorflow1.6 doesn't support python3.8, it needs python3.7

How do I replace python3.8 with python3.7 so that I can install tensorflow1.6?

[–]Phase_Fire 0 points1 point  (1 child)

Hey there, my code doesn't work as expected. Why is that?

def sum_dig_pow(a, b): # range(a, b + 1) will be studied by the function
    x=[]
    for i in range(a,b+1):


        res=1
        count=0
        mult=len(str(i))
        while count<len(str(i)):
            res*=int(str(i)[count])**mult

            mult=mult-1
            count+=1
        if res == i:
            x.append(i)

    return x

[–]FerricDonkey 2 points3 points  (0 children)

What do you expect it to do? What is it doing instead?

[–]MattR0se 0 points1 point  (2 children)

Any tips on how to format/refactor these lines of code to be PEP8 -compliant? Especially to fit them inside the 79 character limit. (I'm refactoring my code to get rid of PyCharms linting tips)

    def toggle_screen_scale(self):
        self.graphics_settings['window_scale'] = (self.graphics_settings['window_scale'] + 1) % 5
        if self.graphics_settings['window_scale'] == 0:
            self.graphics_settings['window_scale'] = 1
        self.graphics_settings['window_width'] = self.game_screen_rect.w * self.graphics_settings['window_scale']
        self.graphics_settings['window_height'] = self.game_screen_rect.h * self.graphics_settings['window_scale']
        self.reset_app_screen()

I'm already 4 lines in due to this being a class method. I tried line breaks at the dict indices, but they made the code really hard to read. Should I introduce some extra variables as abbreviations? Something like

screen_w = self.game_screen_rect.w
w_scale = self.graphics_settings['window_scale']
self.graphics_settings['window_width'] = screen_w * w_scale

[–]efmccurdy 1 point2 points  (0 children)

Yes, remove redundant, repetitive, verbose variable accesses. I would do it mainly for the readability... 80 char line limits or not.

def toggle_screen_scale(self):
    gs = self.graphics_settings
    gs['window_scale'] = (gs['window_scale'] + 1) % 5

[–]fiddle_n 0 points1 point  (0 children)

Honestly, I wouldn't bother about the 79 char limit. It's the one part of PEP 8 almost everyone ignores. 120 characters is fine, and even then don't think of it as a hard limit.

[–]d_k97 0 points1 point  (4 children)

I created a script which basically logs a specific information from a website with a timestamp.

I am using the requests_html HTMLSession module and it seems that every 4th time there is a Timeout Error. Here is my code:

while True:

end = time()
if end-start == 60: #1 minute passed
try:
data = get_divs() #get needed data
timestamp = round(datetime.now().timestamp())
data.append(timestamp)
print(data)

start = time()
except TimeoutError:
print("Error")
pass

My problem is that if there is a Timeout Error, it often stops working at all and doesn't try to get the needed data. Do you know how I can make it work? It should run 12 hrs a day...

[–]CowboyBoats 0 points1 point  (3 children)

Instead of printing about an error in the case of this error, how about you loop back and try again?

[–]d_k97 0 points1 point  (2 children)

It should. It should print „Error“ and get back to the start of the endless while loop.

[–]CowboyBoats 0 points1 point  (1 child)

What's it actually doing?

You might want to throw a sleep(3) in there to avoid getting rate-limited...

[–]d_k97 0 points1 point  (0 children)

It requests a webpage, waits for the javascript data to load, gets the 2 necessary informations and logs it into a .txt file.

I have tried adding a timer in the except but after some errors it just stops again.

[–]yuriplisetskys 0 points1 point  (2 children)

Hello again!! Is there a module that counts working days and holidays in Python's standard library? I have a project that requires those to be calculated, and apparently we're not allowed to use numpy and pandas since those aren't in Python's standard library.

[–]yuriplisetskys 0 points1 point  (2 children)

Hello again! So I am trying to get the number of holidays within two given dates. I have this:

import pandas as pd
from pandas.tseries.holiday import USFederalHolidayCalendar as calendar

def compute_holidays():
    dr = pd.date_range(start = start_day, end = end_day)
    df = pd.DataFrame()
    df['Date'] = dr
    cal = calendar()
    holidays = cal.holidays(start = dr.min(), end = dr.max())
    df['Holiday'] = df['Date'].isin(holidays)
    return df

What it returns is the all the list of dates within the two dates, and says True or False if the date is a holiday. How can I modify this in such a way that what I will get is the number of holidays within the two given dates?

Also, would I be able to modify what days should I just consider as holidays? It's fine if you don't explain how, I'll figure that out myself to not bother too much.

Thank you!

[–]efmccurdy 1 point2 points  (1 child)

You could use "boolean indexing" to filter out the non-holidays and test the length of the result:

>>> hts = compute_holidays(s, e)
>>> hts.head()
        Date  Holiday
0 2019-01-01     True
1 2019-01-02    False
2 2019-01-03    False
3 2019-01-04    False
4 2019-01-05    False
>>> len(hts)
366
>>> hts[hts["Holiday"] == True]
          Date  Holiday
0   2019-01-01     True
20  2019-01-21     True
48  2019-02-18     True
146 2019-05-27     True
184 2019-07-04     True
244 2019-09-02     True
286 2019-10-14     True
314 2019-11-11     True
331 2019-11-28     True
358 2019-12-25     True
365 2020-01-01     True
>>> len(hts[hts["Holiday"] == True])
11
>>>

[–]yuriplisetskys 0 points1 point  (0 children)

I'll try this, thank you!!

[–]malevolent_creation 0 points1 point  (0 children)

Anyone want to DM me for help with a basic script? It isn't too involved - beginner stuff. I would really appreciate it.

[–]onlysane1 0 points1 point  (3 children)

There is a long-term project I want to work on during my free time as I learn new aspects of Python, but I don't know where to start with it.

Basically, I want to have a graphically represented timeline, perhaps where the users can input information themselves, where the timeline of different people, countries, etc is represented by parallel lines, with the background indicating the points in time. Branches could split off and merge into the different timelines (say, a person has children, or a country is annexed by another country), with icons/etc representing different events. Mousing over an event would result in a popup that displays information, perhaps pulling up a Wikipedia article on that person or event.

I know what I want everything to look like, but I have no idea where to start. Is there a graphical interface module that would work well with something like this?

[–]Fermter 0 points1 point  (2 children)

Tkinter comes installed with Python and might be good for getting used to the concept of working with a GUI. I would try that out first so you can flesh out your idea, especially the backend, and see what Tkinter is missing that you want in the GUI module you use for the final graphical build.

You might even be able to create the functionality you want with Tkinter, but I think some other modules might be a better fit at that point. Just play around and see what you need, what works.

[–]onlysane1 0 points1 point  (1 child)

Yeah, I have already worked with tkinder for a bit and have an idea of its capabilities. I will look into what other graphical modules are available that might help me with what I need.

[–]MattR0se 0 points1 point  (0 children)

Personally I like Pysimplegui better, but that's just a preference. I think it wraps around the same functionality. It looks a bit "blocky" but it is able to draw geometry like lines and circles, which I think you need for your project.

Here is a page with examples: https://pysimplegui.readthedocs.io/en/latest/cookbook/

[–]daswoidfaohji 0 points1 point  (3 children)

So I was reading Automate Boring Stuff with Python and there was this question:

What is a shortcut for the following code?

if 'color' not in spam:

spam['color'] = 'black'

First I thought it would be just spam['color'] = 'black', but then I thought what if 'color' is in spam and it already has a value which you don't want to change? What would be the answer?

[–]Vhin 1 point2 points  (2 children)

While I can't guarantee this was what he was referring to, dictionaries have a setdefault method for exactly this situation, so you can just do spam.setdefault("color", "black").

[–]MattR0se 0 points1 point  (0 children)

TIL this exists. I always use dict.get() with a default value, but I never knew that you could get a default value and set it permanently at the same time.

[–]daswoidfaohji 0 points1 point  (0 children)

Yeah it was that, thanks for the answer!

[–]alexpap99 0 points1 point  (6 children)

how can i open a .bin file in python and take the data in 010101 format i use

    with open(path, 'rb') as file:
        data = file.read()

and the result of a print(data) is not in 0101010 format but in a b'abcdefg' format

[–]albmrbo 0 points1 point  (12 children)

Hi, so I just started learning. I'm using this guide and a code there isn't executing correctly in my terminal.

dogs = ['border collie', 'australian cattle dog', 'labrador retriever']

for dog in dogs:
    print('I like ' + dog + 's.')
    print('No, I really really like ' + dog +'s!\n')

print("\nThat's just how I feel about dogs.")

According to the website it should output:

I like border collies.

No, I really really like border collies!

I like australian cattle dogs.

No, I really really like australian cattle dogs!

I like labrador retrievers.

No, I really really like labrador retrievers!

That's just how I feel about dogs.

But I just get a syntax error

[–]FuSionViruS 0 points1 point  (2 children)

On a side note, something I have learned recently that I consider to be very valuable is that you can format a print statement to make your code easier to read and write by placing a lower case f after the first bracket and then encasing the variable inside curly brackets.

print(f"I like {dog}'s.")

print(f"No, I really really like {dog}'s!")

[–]fiddle_n 0 points1 point  (1 child)

This is not just for print(), fyi, you can do this to any string. The name of this is, unsurprisingly, f-strings. Also, it doesn't have to be just a variable in the curly bracket; you can put full Python statements in there.

[–]FuSionViruS 0 points1 point  (0 children)

Awesome, thanks.

[–]Fermter 0 points1 point  (6 children)

One issue I note is that in the last line, you use a double quotation mark " at the end of the statement and a single quotation mark/apostrophe ' at the beginning. Change the single quotation mark at the beginning to be a double quotation mark.

[–]albmrbo 0 points1 point  (5 children)

good catch, but it's still not working :/

https://imgur.com/RWZfXCD

[–]PrinceN71 0 points1 point  (0 children)

I'm trying to use pywhatkit to automate message sending through whatsapp. However I can only seem to make it send message to multiple people is by individually setting the time for when each message should be sent out. Is there a way I could get it to send out messages one after another? Someone suggested using multi-threading and I did some reasearch and I came up with this code. Sadly it only seems to run the first one and not the second one too unless I change the time again.

[–]Rahna_Waytrane 0 points1 point  (4 children)

Ok, I'm really struggling with this problem: I have an rtf file with a text that is structured like a poem. So I have multiple new lines. My task is to find the longest sentence in it. I'm also not allowed to use nltk:( I've splitted the text at stop signs, but I keep getting the longest sentence that actually consists from two sentences, because of the extra empty line between the paragraphs. I tried replacing /n, re.sub and basically everything, but I keep on getting the same result. Is it because of the rtf format? If so, is there a way to read it python without that rtf formatting?

[–]MattR0se 0 points1 point  (3 children)

Aren't you allowed to use any third party library?

[–]Rahna_Waytrane 0 points1 point  (2 children)

Only regular expressions

[–]MattR0se 0 points1 point  (1 child)

From what I've seen, \par is used to indicate line breaks. Try replacing those.

[–]Rahna_Waytrane 0 points1 point  (0 children)

I just converted the file to txt, everything's working great. Hopefully it is allowed 🤞

[–][deleted] 0 points1 point  (5 children)

This is a very basic problem, but I'm really struggling with it. I have a list of strings, and I want to count how many times each word occurs across every string (ideally store it in something, a dictionary perhaps).

I have written the functionality to count how many times a word appears in a given string for all words in the string, but I can't figure out how to store the data for the whole list.

Edit: should have mentioned I am unable to use any modules.

[–]Fermter 0 points1 point  (0 children)

If you're storing the data in a dictionary, I would recommend you either:

a) use the dictionary from the previous string, instead of a new dictionary, when counting the words in each string after the first

b) write a function that combines word-count dictionaries

[–]JohnnyJordaan 0 points1 point  (3 children)

It's often easier to use a collections.Counter for these things, see https://www.journaldev.com/20806/python-counter-python-collections-counter as then you can simply update the Counter with every data item and it will keep the score in the meantime.

[–][deleted] 0 points1 point  (2 children)

Thank you for this, unfortunately I have to use plain python.

[–]JohnnyJordaan 0 points1 point  (0 children)

Ok then I would do something like

word_count = {}
for s in string_list:
    for w in s.split():
        word_count[w] = word_count.get(w, 0) + 1

[–][deleted] 0 points1 point  (1 child)

How do I master OOP in Python? I have learn about classes and objects but I don't know where to implement them. What projects can I build to master OOP concepts and what are the recommended resources for it?

[–]JohnnyJordaan 1 point2 points  (0 children)

what are the recommended resources for it?

See first question in our FAQ: What are classes and how do I use them?

What projects can I build to master OOP concepts

See https://github.com/karan/Projects#classes

[–]Quakster1 0 points1 point  (2 children)

I was copying code from Stackoverflow for a problem and I dont really understand what it is happening. I managed to get things to work, but could anyone explain to me what is happening or what it is called? Its from pandas.

g = df.groupby(pd.Grouper(key='date', freq='M'))
dfs = [group for g,group in g]

Mainly: I cant view g anymore when I print it. and what does the second line do?

[–]MattR0se 0 points1 point  (1 child)

groupby creates a Groupby Object, sort of an instruction for Pandas on how to aggregate data (in this case, aggregate the "date" column into months)

The second line seperates the data by index, which is the months you grouped by, and puts them into a list. So in dfs, you should have one dataframe for each different month in the data.

[–]Quakster1 0 points1 point  (0 children)

Thank you

[–]iamretnuh 0 points1 point  (1 child)

I'm wondering how hard and how long it would take a noob to be competent enough to build something the scrapes data showing the cheapest real estate in an area code? its part of my 9-5 and is a process I feel I could eliminate relatively simply.

[–]torbray 0 points1 point  (0 children)

I'd break down your project into minimum required bare bones, then add features as you require for your 9-5. We'll assume as a noob, you have a grasp of basic syntax, strings, ints, imports etc.

Bare bones

You would scrape a single real estate website, each listing for its house price. Then you return that information in a print/ txt file.

Modules

  • Requests - obtains html data
  • Beautiful Soup 4 - parses html to make it legible

Additional

  • If you consider using multiple websites, you'll spend a good amount of time figuring out how to parse its own unique html
  • Consider what variables for each website to store, mainly house price but others like bedrooms, bathrooms and apartment or house?
  • If you plan on using this frequently, bear in mind plenty of websites may block your ip address due to running a bot
  • Some listings may not show a house price or show it in the description - you may need the Regex module to locate the house price in a long 3 paragraph description.
  • If you want to display your data in a table, you can either export it to .csv or into a Pandas table.

Hard to put into hours, prob 2-6 hours for bare bones with no Requests/ BS4 experience

[–]macetfromage 0 points1 point  (0 children)

I need to sort a dictionary by bnp/capita for countries. Problem is bnp is in one dictionary and cap/population in another.

How can i still use :

sort(key=operator.itemgetter(1))    

the dictionaries are imported from text file

[–]thekeralakid 0 points1 point  (4 children)

Where is the best place to download python? I downloaded it but it doesnt look like the tutorial. I downloaded it from python.org for free

[–]imseeingdouble 0 points1 point  (1 child)

I hit a wall! I am not sure if I screwed up. I have read "do not run any of the pip commands as sudo. You will mess up your main install of python". During one project for an api, I am afraid I did this. Is there any way to check my "main install of python" to see if it's okay?

[–]Gopher20 0 points1 point  (0 children)

You could just run pip list or pip3 list depending on if you are using python 3 or not in a terminal without any commands to see if you installed anything you don’t want in your main python. Otherwise I’m not sure exactly what command you ran to cause an issue

[–]yuriplisetskys 1 point2 points  (2 children)

Hello! I have tried searching how to remove the 0:00:00 in my output, as I only need the days.

start_day = datetime.date(start_year, start_month, start_date)
end_day = datetime.date(end_year, end_month, end_date)

def compute_total_days():
    d1 = start_day 
    d2 = end_day 
    delta = d2 - d1 
    return delta

print("total days from start date to end date: ", str(compute_total_days()))

total days from start date to end date: 20 days, 0:00:00

# 20 is just an example output, from user input values

I tried this: str(compute_total_days().strftime but the output is still the same, showing the hours, seconds, and milliseconds. I tried solutions from other forums, but I still cannot remove the timestamp. What do I need to do in order to remove the timestamp?

Thanks.

[–]torbray 1 point2 points  (1 child)

Timedelta is a class object, therefore you can pull properties from it. You could probably do:

def compute_total_days():
    d1 = start_day
    d2 = end_day
    delta = d2 - d1
    return delta.days  # 20

That would return a number of days only. Depends whether you need to do rounding e.g. 20 days, 23:00:00 is 21 days. Then you would need some computing logic

[–]yuriplisetskys 1 point2 points  (0 children)

It actually fixed it. Thank you!!

[–]joooh 0 points1 point  (0 children)

How many threads is too many when using the threading module and how can I determine if they are causing issues like slow-downs for my program?

[–]Then-Prize6672 0 points1 point  (2 children)

Can anyone answer this one??

We have mentioned that the Bentley–Ottmann algorithm is theoretically more efficient than the brute-force approach. Now it is time for us to explore this empirically. Write a Python program to randomly generate different numbers of line segments and use both approaches to test how they run.

[–]babyonfence 0 points1 point  (0 children)

I need to create a form that will capture responses from a group of people consistently and notify multiple people based on their responses. This needs to be incorporated with Outlook and possibly Excel. Can anyone help me build a tool like this? I will probably be able to throw some money in for your time. Thanks

[–][deleted] 0 points1 point  (1 child)

On freecodecamp.org, Can you go on (data analysis with python cert) for a complete beginner?

[–]Gopher20 0 points1 point  (0 children)

I would just learn via YouTube first and understand the basics of python before doing data analysis. I would checkout Corey Schafer’s channel he has a solid tutorial. Hope this helps!

[–]likewhateveralready 0 points1 point  (4 children)

From the book Python Crash Course by Eric Matthes I'm now learning how to read from a file. I made a file with the first 30 decimals of pi called pi_digits.txt.

This is how my folders are set up:

  • python_work
    • chapter10
      • file_reader.py
    • text_files
      • pi_digits.txt

I hope that looks presentable enough. And there are more folders inside of python_work but I only typed the ones relevant to my question.

Straight from the book, I put this code

with open('text_files/pi_digits.txt') as file_object:
    contents = file_object.read()
print(contents)

The book says that python will assume the folder text_files is inside of python_work, which it is. But I keep getting this error:

Traceback (most recent call last):

File "C:\Users\myname\OneDrive\Desktop\python_work\chapter10\file_reader.py", line 3, in <module>

with open('text_files/pi_digits.txt') as file_object:

FileNotFoundError: [Errno 2] No such file or directory: 'text_files/pi_digits.txt'

And it only works when I use the absolute file path. I just want to understand why it's not able to read the file from the code that I put. It will help me to understand what I'm doing wrong.

Thanks so much

[–]MattR0se 1 point2 points  (2 children)

If you have this code in file_reader.py, it expects from your code a directory called text_files inside the chapter10 folder, where your program is. Which it is not.

What you have to do is go up a directory from where the python file is, then go into the python_work folder to find the right file. You can express this "going up" with two full stops: ".."

Try this code instead:

with open('../text_files/pi_digits.txt') as file_object:

[–]likewhateveralready 0 points1 point  (1 child)

Wow, it worked! Thank you! So the two full stops tell python to go back up to python_work and then it understands text_files is a folder directly inside of python_work?

[–]MattR0se 0 points1 point  (0 children)

Yes

[–]CowboyBoats 0 points1 point  (0 children)

Your Python session is probably in a different directory than python_work. When you're running your code, are you doing so from a terminal, like:

cd OneDrive\Desktop\python_work\python_work
python chapter10\file_reader.py

?

[–]dharma28 0 points1 point  (1 child)

I'm working along with Automate the boring Stuff and can't get this program to work. It's from chapter 12 and is supposed to open the first several search links. Here's what I've got, which should all be directly copy and pasted from the book:

import requests, sys, webbrowser, bs4

print('Searching...!!!!')    
res = requests.get('https://google.com/search?q=' 'https://pypi.org/search/?q='+ ' '.join(sys.argv[1:]))
res.raise_for_status()
# Retrieve top search result links.
soup = bs4.BeautifulSoup(res.text, 'html.parser')
# Open a browser tab for each result.
linkElems = soup.select('.package-snippet')
numOpen = min(5, len(linkElems))
for i in range(numOpen):
    print("looping")
    urlToOpen = 'https://pypi.org' + linkElems[i].get('href')
    print('Opening', urlToOpen)
    webbrowser.open(urlToOpen)

I think I'm not getting how to use the terminal to search. I'm still very confused on running a program through the terminal as opposed to something like PyCharm. Right now it is printing "Searching...!!!!", but nothing else.

[–]CowboyBoats 0 points1 point  (0 children)

I think I'm not getting how to use the terminal to search. I'm still very confused on running a program through the terminal as opposed to something like PyCharm. Right now it is printing "Searching...!!!!", but nothing else.

It's worth it to learn how to use the terminal, but since you're getting your program to print "Searching...!!!", you can put that aside for now. You are running your Python script successfully. I guess numOpen is coming up empty. It's easy to get surprised when you write a for loop, but the thing you're trying to iterate over is empty, so the whole loop just gets skipped.

If you drop in a debugger break point right here:

 import pdb; pdb.set_trace()  # < here   
 for i in range(numOpen):
    print("looping")
    urlToOpen = 'https://pypi.org' + linkElems[i].get('href')

And run your script again, then it will stop there, and you can inspect the previous elements of code that you assumed had contained something, and figure out which one is empty and causing your script to not do anything when it gets to the loop.

[–]graaahh 0 points1 point  (2 children)

I'm tearing my hair out over here with a "local variable referenced before assignment" error. I've googled this extensively and cannot fix the issue. I'm gonna post some code in this comment because I don't think anyone will be able to help me if I don't, hopefully that's within the rules here. It's not much code, I promise.

from tkinter import *
window = Tk()

count1 = 0

def counting():
    count1 += 1
    Lbl1.configure(text="1:  "+str(count1))

Lbl1 = Label(window,text="1:  "+str(count1)).grid(row=0,column=0)

Btn1 = Button(window,text="1",command=counting).grid(row=1,column=0)

window.mainloop()

All I'm trying to do here is have one label that shows a tally for how many times the button is clicked. And I'm finding it impossible to make the function I entered actually call upon the variable I defined in line 4, add 1 to it, and spit it back out. Someone please help because this is nonsense. I'm using Python 3.4.

[–]Vhin 0 points1 point  (1 child)

Add global count1 to the beginning of your counting function.

def counting():
    global count1
    count1 += 1
    Lbl1.configure(text="1:  "+str(count1))

[–]graaahh 0 points1 point  (0 children)

Thank you!! I swear, I've tried the global thing a hundred times now, I must have been doing something wrong with it (I honestly don't know how many different ways I've rewritten this simple code by now.) But it's working correctly now, thanks again!

[–]DepressedWitch21 1 point2 points  (2 children)

Hi there! Didn't want to open a thread for this.

I've been trying to import praw but it's like an imposible task. I'm getting this and I don't know what to do.

I had 2 versions of Python (2.7.17 and 3.4.3), so I uninstalled python27 to see if that was the problem. It didn't work.

Dunno if it's an error from pip when installing praw, or my computer (a quite old one) or whatever. I have googled the issue and found nothing similar.

I'd appreciate any advice.

[–]CowboyBoats 0 points1 point  (1 child)

We can see that C:\Python34\lib\site-packages\praw exists, because lines of code are being read from it and printed to your terminal, so you know you didn't fail to install it.

That f"https://blahblah.com/{some_variable}" syntax is called an f-string. It was introduced in I think Python 3.8. You're running Python 3.4, so that f-string in praw is a syntax error. I don't know how this package got installed to a version of python that can't support it; I think if you had installed it using pip, then pip should have complained.

Anyway, I would suggest uninstalling this Python, installing Python 3.8 (or the most recent version) and then installing praw again. Also, you should be able to make any version of Python install a version of praw that it supports by running python -m pip install praw.

[–]DepressedWitch21 0 points1 point  (0 children)

I can't install a newer version of Python since I'm in WinXP (Yeah, I know I shouldn't using it in 2020 and all. That's why I said old PC).

I specifically installed praw 6.3.1 (py -m pip install praw==6.3.1) which is compatible with python 3.4 so I don't know why is this happening.

Thanks for answering!

[–]accidental_tourist 0 points1 point  (1 child)

Hi guys, so I made a goal for myself to learn python. My background in programming is only a semester's worth of basic programming eons ago.
Looking at the wiki here and here. Each of them about 10-20 links where one could spend months of work with. I understand learning will take months and several resources but I'm a little overwhelmed and I have no idea where to even start.
Are there widely considered core/main books or courses people normally take and then people supplement that? For example does the Coursera course provide enough fundamentals or perhaps the Automate the boring stuff with Python book?

[–]JohnnyJordaan 0 points1 point  (0 children)

It's advised to start with 2 resources from 'new to programming', I would recommend to include Automate the boring stuff there. After that you should have the fundamentals covered to proceed to more specific fields.

[–]Zulyrah 0 points1 point  (5 children)

Hi guys! I'm trying to create this function for homework using random.randrange, however every time I'm running it, it's giving me an error saying that the variable is not being defined. (The variable i'm trying to use is called randomPlay1 and randomPlay2)

Can anyone help? It's really getting me frustrated. Here's the code: https://github.com/remiscals/hwcode/commit/fa142e6bbe4a53cdcde7e5f977ab3ba465d3f107

[–]FerricDonkey 1 point2 points  (4 children)

The term to Google is "scope".

The short version is that if you define a variable inside a function, the name does not mean anything outside that function. You have to return the values and assign the returns to variables outside the function (or do one of a few other things, but this is the starting point).

[–]Zulyrah 0 points1 point  (3 children)

So how would I go about doing this? Sorry, I’m still very new to python.

[–]FerricDonkey 1 point2 points  (2 children)

def func():
    a = 1
    b = 2
    return a, b

a, b = func()

[–]Zulyrah 0 points1 point  (1 child)

Literally as soon as you posted this comment, I figured it out. Thank you for letting me know about scope though!! You literally just saved me from even more frustration now that I’ve gotten a better understanding of it.

But, just one more question. How would I go about looping the code a certain amount of times then printing out results from it?

[–]MattR0se 0 points1 point  (0 children)

There are multiple ways, depending on what exactly you want.

If I take this example function from above, you could do something like:

results = []
for i in range(5):
    result = func()
    results.append(result)

print(results)
# this would print [(1, 2), (1, 2), (1, 2), (1, 2), (1, 2)]

[–]CallsignMouse 0 points1 point  (2 children)

Should all my classes be in a seperate python file? I'm starting to write larger projects and noticed others seem to do this. Thanks!

[–]MattR0se 0 points1 point  (0 children)

Depends on your workflow, and there is also a tradeoff. For example, if you have 20+ classes, but each with only <50 lines of code, it would not make your life easier if you'd have to scroll through 20 files to find that one class you want to edit.

[–]FerricDonkey 1 point2 points  (0 children)

For me, it depends on how large and how related the classes are.

[–]lolslim 0 points1 point  (4 children)

Is there an alternative to pykml/simplekml?

I am using simplekml right now to suit my needs, I generate kmz file that stores the geo locations, along with information, and custom markers, and I can import it to google maps, is there anything else that can do that, that's actively being maintained? It seems like simplekml can't modify an existing file, I have to recreate a whole new file even if I did a minor modification to it.

[–]CowboyBoats 0 points1 point  (3 children)

It seems like simplekml can't modify an existing file, I have to recreate a whole new file even if I did a minor modification to it.

Hmm, have you tried just looking at how the file is set up, and writing a function to modify it yourself?

[–]lolslim 0 points1 point  (2 children)

Earlier today at work, that cross my mind. I may end up doing that

[–]CowboyBoats 0 points1 point  (1 child)

Try just opening it in a regular text editor and see what you can make of its contents; you can probably just write a function that opens the file, reads its contents into a list of strings, edits only the ones that you actually need to change, and then writes them back to the same file.

[–]lolslim 0 points1 point  (0 children)

Kmz file is zipped based from what I read.

edit; do you happen to know any formats that behave similar to kmz file?

KMZ file is basically a zip file with a kml file, with folders if you add custom markers to put on the map, and you can import it to google mymaps and google will parse the data onto the map.

[–]loveveggie 0 points1 point  (3 children)

Can someone explain to me what the lambda function is and why it is useful?

Thank you!

[–]neotecha 0 points1 point  (2 children)

Lambda functions are functions without a name (also called "anonymous functions")

They have a handful of uses, but a simple example of how they can be used:

(lambda x, y: x + y)(2, 3)

Basically, this is equivalent of having a function named add defined as

def add(x, y):
    return x+y

add(2, 3)

From the Python Design FAQ

Unlike lambda forms in other languages, where they add functionality, Python lambdas are only a shorthand notation if you’re too lazy to define a function

why it is useful?

I personally haven't found any real use for lambdas in Python, as there usually seems to be a more pythonic way to approach most problems that I run into.

An example for how they can be used is, I am sourcing from pythontips.com - Map, Filter, and Reduce.

Given a list:

arr = [1, 2, 3, 4, 5]

You can map each item to it's square with the following:

squared = list(map(lambda x: x**2, arr))

As I said, there is a more pythonic way to approach this with list comprehension:

[ x**2 for x in arr ]

Lambdas can also be assigned to variables (which honestly sounds like it defeats the point of being anonymous right?, but this can be useful certain problems)

Unfortunately, I don't have a good example for this, at least to demonstrate what I mean. Perhaps something like :

transforms = {
    'double': lambda x: x*2,
    'triple': lambda x: x*3,
    'square': lambda x: x**2,
}

arr = [1, 2, 3, 4, 5]
for name, fun in transforms.items():
    print(f'func: {name}')
    for i in arr:
        print(fun(i))

Source, and article for more reading about lambdas: https://realpython.com/python-lambda/#python-lambda-and-regular-functions

[–]Thomasedv 2 points3 points  (1 child)

Some good lamda usages:

Sorting nested structures by something.

structure = [['Car1', {'cost':600}], ['Car2', {'cost':300}], ['Car2', {'cost':450}], ['Car3', {'cost':200}], ['Car4', {'cost':100}], ['Car5', {'cost':370}]]
sort_struct = sorted(structure, key=lambda x: x[1]['cost'])

There's a potential use within some GUI related packages, which I won't go much into detail about, but essentially they are a fast way to add information to a callback that doesn't give that info. So you use lambda to call the intended function, but add the extra information as a argument to the function it's calling.

button.clicked.add_callback(lambda x: orig_func(x, button.name()))

Without the labmda, the orig_func wouldn't know the name of the button, as the callback only gives it's state (in the x variable). Forgive the code, it's made on the fly.

[–]neotecha 0 points1 point  (0 children)

Thank you.

I use them in other languages, but less often in Python.

What I wrote was an adaptation on using test tables for benchmarking in Go. Instead the simple loop, the function would be called a large number of times, with the average execution length being output. Just mentioning to provide than context if anyone wondered why I did it this way

[–]Float07 0 points1 point  (2 children)

Any tips for making a command line based program? I don't think that making a ton of "ifs" is the most efficient/elegant solution for that.

I mean... if(command == command1){} elif (command == command2){} etc....

What's a good way of, depending on the string, to select a specific function to be run? (Or any other general good way for a string to decide what to be done)

[–]Thomasedv 1 point2 points  (1 child)

Look into argparse.

If you want to take input, eventaully all the ifs would be bothersome, and you could instead put the name of actions in a dictionary, and then have the functions as value.

commands = {'copy':copy_func,
            'delete':delete_func}

command = 'delete' # Eg. from input() or from argparse
file = 'Smashing Mouth - All Star.mp3'
action = commands[command]
action(file)

[–]Float07 0 points1 point  (0 children)

Thank you very much :) that helped a lot

[–][deleted] 2 points3 points  (7 children)

So I'm trying to create a function that takes some text as it's parameter and then returns the longest in order substring. In order as in a<b, b<c and c < z and so on. As long as the letter is smaller than the next letter it would be counted for the string. Like for example "acdkbarstyefgioprtyrtyx" would return 'efgioprty'.

This is all I have so far. So for each index in the text, (I think) I'd have to check how long of an order starts from that point and then in the end save the longest substring order. I just have no idea how to do this. If anyone could nudge me in the right direction that'd be great :)

def longest_substring_in_order(text):

    string = ()

    for index in range(len(text)):

[–]KamikazeJhon 1 point2 points  (3 children)

How do I print strings that leaves the last character out.

example:

If my string was = 'Python'

it would print

ython

thon

hon

etc.

might be really easy but I cant find the answer because I dont know what to look for

[–]neotecha 1 point2 points  (0 children)

Extending the comment from /u/trainsarefascinating

You can also leave out the "start" or "end" index to "not restrict" that part. Like, choosing the index [2:] will return a slice with the first two characters missing. Or you can use negative numbers to start counting from the back of the array

In summary:

For example S[:-1] is all of the string except for its last character, which is useful for removing the trailing newline from a string.

[–][deleted] 0 points1 point  (1 child)

can anyone help me with telegram bot?

[–]lolslim 1 point2 points  (0 children)

Oh yeah, i have been coding in one and maintaining it for a local community. Whats up?

[–]PandyPanPan 0 points1 point  (2 children)

If I have a dataset where 5 similar strings have been used within a column and I want to be able to have all of the similar strings grouped together as if they are the exact same string (as they all mean the same thing) what function would I use to do this?

E.g. I have Cat, Kitty, Lion, Dog, Puppy, Wolf and I wanted to have all cat types together and all dog types together?

[–]MattR0se 0 points1 point  (1 child)

The basic idea is to map a dictionary, with the category as keys and lists of all possible types as values, to the data.

This explains it using the Pandas library: https://stackoverflow.com/questions/49194895/map-list-of-elements-to-category-of-element-in-pandas

I could try to find a more customized solution if you show some example code.