python console to call function - python

I know this is an easy fix, but could someone tell me how to call a python file in the python Console who have this symbol: -.
Here is my mistake:
>>> import main #no error here
>>> import a1-devoir1
File "<input>", line 1
import a1-devoir1
Syntax Error: invalid syntax

You must name your files so that they only contains letters, underscores, or numbers (but not as the first character). All libraries and modules must follow this.
So rename your .py file to a1_devoir and then try import a1_devoir

Related

why is the error thinking Its not string?

path of file is:
"C:\Users\deana\OneDrive\Marlon's files\Programming\Python\PITT\PITT_LIbrary\Lists\test.txt"
lines of code are:
import os
os.chdir("C:/Users/deana/OneDrive/Marlon's files/Programming/Python/PITT/PITT_LIbrary/Lists")
exec(open('test.txt'))
the error is this:
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
exec(open('test.txt'))
TypeError: exec() arg 1 must be a string, bytes or code object
also if I try on one line as such:
exec(open(r"C:/Users/deana/OneDrive/Marlon's files/Programming/Python/PITT/PITT_LIbrary/Lists/test.txt"))
i'ts the same error. (with and without r)
super frustrationg as it reads like i'm not inputting string... but it is string!?!
also I've done this litteraly the same way before, restarted IDLE shell, no difference.
ugh! I always get stupid errors with file paths.
I should have been using os.startfile() to open this.
It was confusing by using .open(). as I was attempting to open in default app.
before, i've used exec.open() to open .py files and guess I got them confused.
exec is just used to open other scripts... need stronger coffee next time.
Try this:
import os
os.chdir("C:/Users/deana/OneDrive/Marlon's files/Programming/Python/PITT/PITT_LIbrary/Lists")
exec(open('test.txt', 'rb'))
You can convert the txt file to bytes by opening it with rb (read bytes).

python module re throwing odd AttributeError

I've always used the re module to do things such as re.match and re.sub, the basic stuff, and it's always worked fine for me.
All of a sudden, I'm getting an AttributeError when trying to use basic methods such as match and sub.
Here is some example code I made:
import re
regex = '^[a-z]{3}'
r = re.match(regex, 'asd')
print r
Here's the stacktrace:
Traceback (most recent call last):
File "te.py", line 4, in <module>
r = re.match(regex, 'asd')
AttributeError: module 're' has no attribute 'match'
I've never had problems with the module. I tried in both python 2.x and 3, same error. I'm not very knowledgeable about how imports work, so this is likely a simple mistake by me.
Thanks
Delete your re.py file in the same directory as the te.py file. You commited a typo while naming test files. Your error points that your current file is named te.py, and since t is close to r in the keyboard, this might explain everything.
Just to prove my curiosity I created an empty re.py file in the same directory as te.py, which holds your code. And I got the same error as you did.
My guess is that you're getting something you don't expect for the re module that you're importing.
Maybe try this:
import re
print re.__file__
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.pyc
And see if the result you get is sensible.

Python Library (foundation\FormParameters.py) error

The first line i enter in IDLE is
from foundation import FormParameters
And i get a error like this
>>> from foundation import FormParameters
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
from foundation import FormParameters
File "C:\Python32\lib\foundation\FormParameters.py", line 19
con_str = StringIO()
^
TabError: inconsistent use of tabs and spaces in indentation
As it is a standard library can i change it? or is there any other way round??
As it is a standard library can i change it?
You can just open the referenced File ("C:\Python32\lib\foundation\FormParameters.py") and edit it - in this case I would suggest replacing tabs with spaces, as tabs and python are an evil combination.
As some others commented, this is NOT a part of the standard library - but even if it were, the same rules would apply - find the file and you're free to edit it (you probably shouldn't though if you intend to run your programs on other machines with an unmodified standard library). For C extensions this pörocess is somewhat more complicated as you would need to compile them.

Can't open file: "NameError: name <filename> is not defined"

I am creating a program to read a FASTA file and split at some specifc characters such as '>' etc. But I'm facing a problem.
The program part is:
>>> def read_FASTA_strings(seq_fasta):
... with open(seq_fasta.txt) as file:
... return file.read().split('>')
The error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'seq_fasta' is not defined
How to get rid of this problem?
You need to specify the file name as a string literal:
open('seq_fasta.txt')
You need to quote the filename: open('seq_fasta.txt').
Besides that, you might choose a different name but file as using this name shadows a builtin name.
Your program is seeing seq_fasta.txt as a object label, similar to how you would use math.pi after importing the math module.
This is not going to work because seq_fasta.txt doesnt actually point to anything, thus your error. What you need to do is either put quotes around it 'seq_fasta.txt' or create a text string object containing that and use that variable name in the open function. Because of the .txt it thinks seq_fasta(in the function header) and seq_fasta.txt(in the function body) are two different labels.
Next, you shouldnt use file as it is an important keyword for python and you could end up with some tricky bugs and a bad habit.
def read_FASTA_strings(somefile):
with open(somefile) as textf:
return textf.read().split('>')
and then to use it
lines = read_FASTA_strings("seq_fasta.txt")

Creating a Python function that opens a textfile, reads it, tokenizes it, and finally runs from the command line or as a module

I have been trying to learn Python for a while now. By chance, I happened across chapter 6 of the official tutorial through a Google search link pointing
here.
When I learned, from that page, that functions were the heart of modules, and that modules could be called from the command line, I was all ears. Here's my first attempt at doing both, openbook.py
import nltk, re, pprint
from __future__ import division
def openbook(book):
file = open(book)
raw = file.read()
tokens = nltk.wordpunct_tokenize(raw)
text = nltk.Text(tokens)
words = [w.lower() for w in text]
vocab = sorted(set(words))
return vocab
if __name__ == "__main__":
import sys
openbook(file(sys.argv[1]))
What I want is for this function to be importable as the module openbook, as well as for openbook.py to take a file from the command line and do all of those things to it.
When I run openbook.py from the command line, this happens:
gemeni#a:~/Projects-FinnegansWake$ python openbook.py vicocyclometer
Traceback (most recent call last):
File "openbook.py", line 23, in <module>
openbook(file(sys.argv[1]))
File "openbook.py", line 5, in openbook
file = open(book)
When I try using it as a module, this happens:
>>> import openbook
>>> openbook('vicocyclometer')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
So, what can I do to fix this, and hopefully continue down the long winding path to enlightenment?
Error executing openbook.py
For the first error, you are opening the file twice:
openbook(file(sys.argv[1]))
ph0 = open(book)
Calling both file() and open() is redundant. They both do the same thing. Pick one or the other: preferably open().
open(...)
open(name[, mode[, buffering]]) → file object
Open a file using the file() type, returns a file object. This is the
preferred way to open a file.
Error importing openbook module
For the second error, you need to add the module name:
>>> import openbook
>>> openbook.openbook('vicocyclometer')
Or import the openbook() function into the global namespace:
>>> from openbook import openbook
>>> openbook('vicocyclometer')
Here are some things you need to fix:
nltk.word_tokenize will fail every time:
The function takes sentences as arguments. Make sure that you use nltk.sent_tokenize on the whole text first, so that things work correctly.
Files not being dealt with:
Only open the file once.
You're not closing the file once it's done. I recommend using Python's with statement to extract the text, as it closes things automatically: with open(book) as raw: nltk.sent_tokenize(raw) ...
Import the openbook function from the module, not just the module: from openbook import openbook.
Lastly, you could consider:
Adding things to the set with a generator expression, which will probably reduce the memory load: set(w.lower() for w in text)
Using nltk.FreqDist to generate a vocab & frequency distribution for you.
Try
from openbook import *
instead of
import openbook
OR:
import openbook
and then call it with
openbook.openbook("vicocyclometer")
In your interactive session, you're getting that error because you need to from openbook import openbook. I can't tell what happened with the command line because the line with the error got snipped. It's probably that you tried to open a file object. Try just passing the string into the openbook function directly.

Categories