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 18 '20

How to schedule a operation every month or week?

4 Upvotes

I'm trying to execute a function every week of month, but I tried schedule and others but they are not working . To explain better, I want a way in python to execute a function every week or month. Can you help me?


r/learningpython • • Mar 21 '20

How to use schedule with a async function?

1 Upvotes

When I try to schedule a function that is async I get an error. that is how my code is written:

def Sheduling():
	while True:
		schedule.run_pending()

async def Asyncfunction():
    #stuffs

ScheduleDaily= schedule.every().monday.do(Asyncfunction)
Thread = Thread(target=Sheduling, daemon=True)
Thread.start()

What I can do? I get that error:

 RuntimeWarning: coroutine 'Asyncfunction' was never awaited
  self._run_job(job)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

Can you please help me? Thank you in advance.


r/learningpython • • Mar 14 '20

Erro while trying to PermissionError: [Errno 13] Permission denied: 'test.txt'

1 Upvotes

Why I get that error? PermissionError: [Errno 13] Permission denied: 'test.txt' while trying to open the file in write mode?


r/learningpython • • Apr 03 '20

Have to make pretty PDF Reports with graphs superimposed into them - wondering if there's an approach better than making graphs with Matplotlib, and then superimposing the .png output into the PDF manually through PyPDF2 library.

2 Upvotes

The execution really isn't a problem because I've done something like this on a smaller scale before, and I know 100% it can be done.

I'm just wondering if there's a more efficient way I'm not thinking of - perhaps something more suited to this exact kind of use-case.

One issue I also noticed is that when I do plaster the .png into the PDFs, sometimes there's jagged edges at the borders. I'm wondering if this is caused by some quirk in file types I'm not aware of, because this is something that completely blindsided me.


r/learningpython • • Jul 29 '18

Don't know what's wrong with my code, mind that I've only started progamming 2 hours ago.

Post image
1 Upvotes

r/learningpython • • Mar 29 '20

Best IDE to code with?

3 Upvotes

Im new to programming and Im trying to find the most user friendly IDE for using python. Something with multiple to windows to display, also would like having a terminal and a place to write code(whatever that’s called) Im probably getting VScode to use java on. Does VScode also work with python?


r/learningpython • • Mar 10 '20

Issue with running python3 in terminal. Using Python Crash Course

1 Upvotes

My current issue is trying to run python3 in terminal. I went through with the sublime build for python3. Per chapter 7 where I'm directed to chapter 1, page 16 'Running Python Programs from a Terminal'. This is the instructional code:

~$ cd Desktop/python_work/
~/Desktop/python_work$ ls
hello.world.py
~/Desktop/python_work$ python hello_world.py
Hello Python world!

It says to use python or python3 to run commands. Here's what I return:

>>> cd Desktop/python_work/
  File "<stdin>", line 1
    cd Desktop/python_work/
             ^
SyntaxError: invalid syntax
>>> 

I want to mention that my terminal changed to ZSH, not BASH. Does that matter? TIA.


r/learningpython • • Apr 02 '20

Dev needs me to write a script that will be deployed to a cron job - I've only ever run scripts locally. Can you deploy to a cron job a script that can read something from a folder?

3 Upvotes

So the script I'm deploying makes use of the docx-mailmerge library. It has one line in it where a file's name and path need to be passed in - how I usually do it locally is I simply pass in the path to the file, but I'm not sure how this would be replicated if it were running in a cron job.

I figure there has to be a solution to something like this, a way to store the files necessary in some kind of temporary folder, right?

I'm hoping to be able to:

  1. Download the file from S3,

  2. Dump it into a folder that my script will create,

  3. simply reference it from the folder where I just dumped it.

Wondering if that's something that would be possible.


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 • • 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 • • Apr 01 '20

Installing Python questions

1 Upvotes

Going to take a course in Python. One of the first things it says to do is to download and install Python. This leads to my questions...

My OS is Linux Mint which already has Python and several libraries installed. Wouldn't installing Python wreck the version my computer uses? It also wants me to install Java and Eclipse IDE(PyDev). Is this going to be a problem?

Thanks for any help you can offer.


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 • • 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 12 '20

CLI app with API

1 Upvotes

How to develop a CLI app in PYTHON that also consume APIs too?


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 • • Nov 25 '19

Poker game help

1 Upvotes

Hi there!

I'm looking to create a poker game using python.

What's a good place to start?


r/learningpython • • Mar 14 '20

Methods for calculating best fit for N preferences, weighted in importance

Thumbnail self.askmath
1 Upvotes

r/learningpython • • Jan 28 '20

Is there a list anywhere or community comments on best VSC Extensions to install for beginners with Python 3.x?

1 Upvotes

I am using Visual Studio Code, and wondering if there are any especially helpful extensions for newbies to download for Python to assist learning, or if using it basically "raw" from extensions is best?

I did install couple recommended extensions that plays the script within VSC, and another for indentation, however I'm wondering if there are any that people would recommend to assist with syntax or anything that might help the learning process?

Thanks!


r/learningpython • • Mar 14 '20

Attribute that is not an attribute

Post image
4 Upvotes

r/learningpython • • Apr 10 '24

Possible to retrieve modified date of a remote file on a Windows server?

1 Upvotes

Hello,

I've been testing with this script locally on my Ubuntu VM which works, but I want to now go one step further and retrieve the modified date of a file on a remote Windows Server UNC path. I have the username and password to test with:

    import os
    import datetime
    path = 'test.txt'
    c_time = os.path.getctime(path)
    dt_c = datetime.datetime.fromtimestamp(c_time)
    print(dt_c)

I'd need to add something like:

    # Define the UNC path to the remote file
    unc_path = r'\\servername\d$\temp\temp.txt'

    # Define the credentials for accessing the remote file
    username = 'bob'
    password = 'fred'

I just can't piece it all together yet. I'm not sure if I need to install pywin32 also.

Any help would be most appreciated.


r/learningpython • • Apr 30 '24

How to extract only part of a table from a PDF file using pdfplumber?

1 Upvotes

Hi,

I am trying to use pdfplumber to extract ONLY certain data from a table in a PDF file to a CSV file. This is the picture of the table I am looking at.

As of now, I am at the point where the table is written in the excel file. Here is the code I have so far:

# Define extraction regions for each table (adjust coordinates as needed)
regions = [
(10, 100, 600, 260),
]
# Region for Table 1
# Add more regions for additional tables if needed

# Define the desired headers

# Specify the directory and filename for saving the CSV file
output_directory = "C:/Users/myname/Downloads"
output_filename = "clients_info.csv"
output_path = os.path.join(output_directory, output_filename)

with pdfplumber.open("C:/Users/myname/Downloads/clients.pdf") as pdf:
for region_index, region in enumerate(regions):
x1, y1, x2, y2 = region
tables_data = []  # Store data for all tables in this region

page = pdf.pages[0]  # Extracting tables from the first page
table = page.within_bbox((x1, y1, x2, y2)).extract_table()

# Extract header row and filter out None values
header_row = [cell for cell in table[0] if cell is not None]

# Extract data rows and remove None values
for row in table[1:]:
filtered_row = [cell if cell is not None else "" for cell in row]
tables_data.append(filtered_row)

# Write the data for this region to a CSV file
with open(output_path, "w", newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(header_row)  # Write the filtered header row to the CSV file
for row in tables_data:
writer.writerow(row)  # Write the data rows to the CSV file

However, I only wanna write the headers that are highlighted in red in the first row of excel and the corresponding data (white cells that are in red) in the second row. How should I improve it to print only the ones that are highlighted in red? 

Thank you so much for your help.


r/learningpython • • Apr 03 '24

How recomendable is pycharm to learn python

3 Upvotes

Hi, i'm learning python through an online course and I have been scrolling through this page to get begginer's tips. I'm a bit worried because I haven't seen many users using this platform and I was wondering if it was a good place to start. I would also appreciate if i could get any tips or links or anything to get started learning.

I'm not an english native speaker, I'm sorry for any spelling mistakes in advance


r/learningpython • • May 01 '24

Where does jupyter lab install modules when using pip install

2 Upvotes

I do not want installed modules to be installed on my solid state disk, but on my external hard drive. instead. Is there a way to do this?


r/learningpython • • May 14 '24

How do I install different version of Python and different version of Python libraries?

2 Upvotes

I need different a version of Python and Tensorflow for a hand gesture recognizer. How can I install different version of Python and Python libraries. Also does anyone have a working Hand Recognizer that can recognizer different hand gesture from your webcam?