Python

Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in other languages. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive set of standard libraries, including NumPy, SciPy, Django, PyQuery, and PyLibrary.

Share tech news, updates, or what's on your mind.

Sign up to Post

How to extract postcode out of the string?
example: how to extract "D18 W528"
from this string "20 Corbawn Close Dublin 18 D18 W528" in csv file
0
Get your problem seen by more experts
LVL 12
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Class and method: main() in python

I have seen examples in python where they use class main() or method main(). I wonder if it has the same meaning as in Java, where the main method gets executed first, or it is just a name that can be different than main() ?

Thank you
0
how to delete those lines in a text file having only 1 word like #test or any1word like amaze. I want to keep those lines having words more than 1 like amazing python
0
https://www.experts-exchange.com/questions/29106263/replacing-hypertext-links-with-simple-text-'URL'.html#a42605453

I need to remove all http starting from http:\/
I am able to remove all http starting from http://  and the regular expression for this is given in the above link.

url_rex = re.compile(r'(http|ftp|https)://[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?')

How can I modify this regular expression remove http starting from http:\/

Also, the below code deletes the characters @, # from the words starting from @ or # which I intend to keep.

import re, string, html
uni_escape = re.compile(r'\\u[0-9a-f]{4}')
url_rex = re.compile(r'(http|ftp|https)://[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?')
with open("input.txt", "r") as fin, open("output.txt", "w") as fout:
    for text in fin:
		unesc_html_text = html.unescape(text)
		encoded_text = bytes(unesc_html_text, 'ascii', errors='ignore')
		decoded_ascii_text = encoded_text.decode('ascii')
		unesc_text = re.sub(uni_escape, '', decoded_ascii_text)
		text = url_rex.sub('', unesc_text)
		fout.write(text)

Open in new window


How to change the regular expression to keep @ and # in words?
0
Python Class classname (Object)

I have the codes below if I declare the class Car(object) or just class Car, I get the same result. I am not sure what the keyword (Object) is for.

Thanks


class Car:

    wheels = 4

    def __init__(self, make, model):
        self.make = make
        self.model = model

mustang = Car('Ford', 'Mustang')
print (mustang.wheels)
# 4
print (Car.wheels)
# 4
0
I am iterating over rows in pandas with itertools.

for index, row in df.iterrows():
    print(row['firstname'])

It will print the firstname of each row. Now I want to compare these names to see if they are equal.
0
Python is Interpreter or Compiler based language

I have read that Python is an Interpreter based language. Does that mean it can be slow to render the results when it is run ?

Thank you
0
Hi
I'd like to install tkinter in my Pycharm

I go to preferences and hit the + install button and there are a chunk of tkinter installs to consider.

Does it matter which one I choose?

Thanks
0
I have a data set containing duplicates values in rows for multiple columns. I am looking to do row wise matching of values for 2 or 3 columns.
0
I want to create my first application (I'm a web dev) in Python.

I'm going to try and create an open source version of Neck Diagrams (neckdiagrams.com). If that is beyond me I'll come back to it soon.

So I need to learn Python and GUI programming in Python.

I was hoping some people could recommend books to learn Python and books to learn GUI Programming in Python.
0
Upgrade your Question Security!
LVL 12
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

i have a list in col A of excel of files names. the file names are purely numbers, so maybe that makes it easier.

need to look in windows folder for those file names and delete files if they match the list.
0
Hi,


Please can any one help that using power shell how to force user  to expire there password only Monday to Wednesday or Certain dates and Times. because recently I have used power-shell script to force user to change password at next login which brings lot of problems for support team. specially we cannot afford this on weekend because of retail industry.

we are over 4000 users and its challenge to force expire the password and set new password on certain days or dates. I hope there must be someone expirence same and some Guru on power shell or Python script to achieve this. please advice with right script.
0
How to incorporate the codes from these questions already solved on experts exchange for the text file I have attached. . Name of the text file is corpus.txt   corpus.txt

This text file is a labelled data. It also contains unicode character, punctuation, html escape character, https, stop words.

Links to the question I am referring to are:

https://www.experts-exchange.com/questions/29096027/How-to-remove-unicode-characters-from-csv-file.html#a42543025

https://www.experts-exchange.com/questions/29106263/replacing-hypertext-links-with-simple-text-'URL'.html#a42605405 

https://www.experts-exchange.com/questions/29106273/error-while-splitting-with-open-function-in-python.html#a42605423

https://www.experts-exchange.com/questions/29106318/AttributeError-'list'-object-has-no-attribute-'split'-and-AttributeError-'numpy-ndarray'-object-has-no-attribute-'split'.html#a42606101

All the accepted solutions for these links have been given by expert gelonida.

--------------------------------------------------
code to remove punctuation, to remove any number, or any stopword is:
-----------------------------------------------------
import string
text = text.split()
re_punc = re.compile('[%s]' % re.escape(string.punctuation))
text = [re_punc.sub('', w) for w in text]
text = [word for word in text if word.isalpha()]
from nltk.corpus import stopwords
stop_words = set(stopwords.words('english'))
text = [w for w in text if not w in stop_words]

I …
0
I had this question after viewing Python ElementTree xml output to csv.

I am attempting to use the same xml.etree solution but I am having a bit of trouble. I don't fully understand how to .find, .findall, and .iter in order to access the nodes and attributes. This is my test code that I ran on a nested xml file (attached) . writing out the row with the rowheaders works fine - that's why it's commented out.

I just ran a new test that worked but it's not very elegant. However, I have all the columns of my csv file. I read in the file as a string because I'm working from a web-based interpreter at home right now. I think I'll try lmxl to see if I can utilize xpath syntax to tighten up the code.

file = sys.stdin.read()
root = ET.fromstring(file)

#!  Python3

"""
Program uses xml.etree module to select data elements from the xml tree, names
 row headers, and  csv.writer then writes them to a csv file. Rows are appended
 to the file as each file in the directory  is processed.,

Program Author:            Gerald I Cheves
Date written:            25 June 2018
Last Revision:            25 June 2018
"""

import xml.etree.ElementTree as ET
import csv
import winsound

tree = ET.parse('C:\\Users\\GCheves\\aladin\\Test-Files\\Person.xml')
root = tree.getroot()

"""
with open('C:\\Users\\GCheves\\aladin\\Output\\xml-csv-output.csv', 'w') as fout:
    writer = csv.writer(fout, …
0
error
AttributeError: 'list' object has no attribute 'split'

error2

AttributeError: 'numpy.ndarray' object has no attribute 'split'
0
for the text like

index     label     text
0              1           @amazon, this product was good. http:/.......
1              1           !env is getting worse.

df_x = x.split('\t')[2] for x in open('test.txt').readlines()

this does not seem to work
0
I had this question after viewing How to remove unicode characters from csv file?.

In the context of best accepted solution i.e for the same dataset, how to replace the https i.e (hypertext) links with 'URL' in the whole document?
0
OSError: `pydot` failed to call GraphViz.Please install GraphViz (https://www.graphviz.org/) and ensure that its executables are in the $PATH.

I am not able to call GraphViz with pyplot. I tried various references on github, video but it does not to work out for me.

My Problem refers exactly like this one stated below:

https://www.youtube.com/watch?v=W_Ioq6l77P0
https://stackoverflow.com/questions/40632486/dot-exe-not-found-in-path-pydot-on-python-windows-7/43509785
https://stackoverflow.com/questions/39345846/cant-get-pydot-to-find-graphviz-on-windows-10


I have installed the pydot through pip
and
installed msi file of Graphviz from this link - https://graphviz.gitlab.io/_pages/Download/Download_windows.html

I have given the path of executables of pydot and graphviz in user variable and system variable also.

I am adding the snapshots.
Capture.PNG
Capture1.PNG
Capture2.PNG
Capture3.PNG
Capture4.PNG
0
I am looking for a Python code/function which will pass an address and get a geocode/postcode from the google api.
0
Introducing Cloud Class® training courses
LVL 12
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

Hi
I asked another python threading question, but this one may explain my issue..

I wrote this code, to see if two second counting threads could work at the same time.

For some reason, only one does the counting.

This is symptomatic of my problems with Python Threads

Why does this code only count one of the instances, and not the 2nd
I always get one Thread that is blocked from execution!

import threading,time



class counter:


    def __init__(self,thread_number) :
        self.thread_number = thread_number

        t = threading.Thread(target=self.count())
        t.start()

    def count(self):

        frameCount = 0
        while True:
            print (self.thread_number,' frame #',frameCount)
            frameCount += 1
            time.sleep(1)


counter(1)


counter(2)

Open in new window


Thank You
0
Hi
My Python chess project new approach is tripping up.
I think it might be to do with Thread entanglement.
My engine instantiates a white and a black player, which are each abc's for their AI, random movers for now.

Then I start a game_loop() to handle the game play.

Does Thread "entanglement" ever happen? I cant see any reason for my Threads to unravel
I suspect this, because I have a thread counting the seconds going by on the console
( will help with clock)
But, when I instantiate my board window, the board window appears, but the counting thread disappears. (take away the # comment in ChessEngine.py to reinstate the board creation
Have they become entangled?

My
ChessEngine.py has the call to init the board commented out, so you can see the seconds being counted out.
as soon as the # is taken away and the board instantiates, the first Thread ceases to count.
It only counts the seconds when there is no board

Are Python Threads delicate and tough to combine?
Something in the board class is locking it all up
Code attached
What could it be?

Thanks

files...

ChessBoard.py

ChessEngine.py

ChessPlayer_abc.py

ChessBoard.py

RandomPlayer.py

ChessPlayer.py
0
Hi
My PyCharm is giving surprising red-underlining on import abc, object, and from abc import
Up til now, my chess engine has been working on a player class, but I'd like it to be an abstract base class. I am re-designing it
Must I do any special entries in the Project Settings panel? my code below doesn't seem to be a problem,



My abc is :
import abc

class ChessPlayer(object):
    __metaclass__= abc.ABCMeta

    @abc.abstractmethod
    def get_white_move(self, white_moves):
        """white player chooses the best move for this turn"""
        return

    @abc.abstractmethod
    def get_black_move(self, black_moves):
        """black player chooses the best move for this turn"""
        return

Open in new window

My derivative class is:
import abc
from abc_base import ChessPlayer:


class RandomPlayer(Object):
# ToBeDone, once setup is correct

Open in new window


Thanks
0
I'm trying to figure out how to use the subprocess module in Python to run a command to execute edx-dl.  Edx-dl is a git project to download video and course content from Edx.org.

In the windows shell (usually powershell), I would do the following without error:
python E:\edx-dl\edx-dl.py -u my@email.com -p "mypw" --ignore-errors

Open in new window


In python, I have tried a number of different ways of inputting the arguments, all to no avail.  I got the furthest with this:

import os
import subprocess

#subprocess.call(["ls", "-alt"])
#subprocess.call(["grep", "six", "requirements.txt"])

os.chdir('E:\edx-dl')
subprocess.call(["python", "E:\edx-dl\edx-dl.py", "-u my@email.com -p mypw"])

Open in new window

In the shell, this would give:
edx_dl version 0.1.7

Building initial headers for future requests.
Getting initial CSRF token.
Found CSRF token.
Logging into Open edX site: https://courses.edx.org/login_ajax
Extracting course information from dashboard.
You can access 12 courses
...{LIST OF COURSES}
But from Python all I get is that first line, and then it hangs.

What is the proper argument format for subprocess?  Do the '-u' and the 'my@email.com' belong in the same or different strings?  'Python' is the actual command, and the edx-dl.py is the python file.

What do I do?
0
Hi
If I do exactly what the python page says, and I get a no such member error:

In doing the concrete class code from this abc page here

If I type
import abc
from abc import ABCMeta
from abc_base 

Open in new window


It underlines in red abc_base and (object) in my class, which is confounding!
Surely having the abc import will make that all legal?

my parent is
import abc

class ChessPlayer(object):
    __metaclass__= abc.ABCMeta

    @abc.abstractmethod
    def do_white_move(self, white_moves):
        """white player chooses the best move for this turn"""
        return

    @abc.abstractmethod
    def do_black_move(self, black_moves):
        """black player chooses the best move for this turn"""
        return

Open in new window



Thanks
0
Hello, I am trying to populate a table in MSWord from Python - I am currently using the below but it is EXTREMELY slow... ive got liek 500 lines to output and its take about 1 line every 3 seconds. Can anyone help with what I am doing wrong?

What I am doing is taking a list I have created from JSON response and populating the a word template with the info. I need to use the table columns because I need the column widths to remain the same -->  then I will be printing to pdf


from docx import Document
from docx.shared import Inches
document = Document('c:\\pythondev\\Invoice_Template.docx')
table = document.add_table(rows=woncount, cols=6)
r = 0

for row,line in enumerate(W):
        try:
                c = 0
                for col, ct in enumerate(line):
                        cell = table.cell(r, c)
                        try:
                                cell.text = ct
                        except:
                                cell.text = str(ct)
                        c = c + 1
                r = r + 1
        except:
                break

document.save("c:\\pythondev\\testworddoc.docx")

Open in new window

0

Python

Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in other languages. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive set of standard libraries, including NumPy, SciPy, Django, PyQuery, and PyLibrary.