Python ValueError: chr() arg not in range(256) - python

So I am learning python and redoing some old projects. This project involves taking in a dictionary and a message to be translated from the command line, and translating the message. (For example: "btw, hello how r u" would be translated to "by the way, hello how are you".
We are using a scanner supplied by the professor to read in tokens and strings. If necessary I can post it here too. Heres my error:
Nathans-Air-4:py1 Nathan$ python translate.py test.xlt test.msg
Traceback (most recent call last):
File "translate.py", line 26, in <module>
main()
File "translate.py", line 13, in main
dictionary,count = makeDictionary(commandDict)
File "/Users/Nathan/cs150/extra/py1/support.py", line 12, in makeDictionary
string = s.readstring()
File "/Users/Nathan/cs150/extra/py1/scanner.py", line 105, in readstring
return self._getString()
File "/Users/Nathan/cs150/extra/py1/scanner.py", line 251, in _getString
if (delimiter == chr(0x2018)):
ValueError: chr() arg not in range(256)
Heres my main translate.py file:
from support import *
from scanner import *
import sys
def main():
arguments = len(sys.argv)
if arguments != 3:
print'Need two arguments!\n'
exit(1)
commandDict = sys.argv[1]
commandMessage = sys.argv[2]
dictionary,count = makeDictionary(commandDict)
message,messageCount = makeMessage(commandMessage)
print(dictionary)
print(message)
i = 0
while count < messageCount:
translation = translate(message[i],dictionary,messageCount)
print(translation)
count = count + 1
i = i +1
main()
And here is my support.py file I am using...
from scanner import *
def makeDictionary(filename):
fp = open(filename,"r")
s = Scanner(filename)
lyst = []
token = s.readtoken()
count = 0
while (token != ""):
lyst.append(token)
string = s.readstring()
count = count+1
lyst.append(string)
token = s.readtoken()
return lyst,count
def translate(word,dictionary,count):
i = 0
while i != count:
if word == dictionary[i]:
return dictionary[i+1]
i = i+1
else:
return word
i = i+1
return 0
def makeMessage(filename):
fp = open(filename,"r")
s = Scanner(filename)
lyst2 = []
string = s.readtoken()
count = 0
while (string != ""):
lyst2.append(string)
string = s.readtoken()
count = count + 1
return lyst2,count
Does anyone know whats going on here? I've looked through several times and i dont know why readString is throwing this error... Its probably something stupid i missed

chr(0x2018) will work if you use Python 3.
You have code that's written for Python 3 but you run it with Python 2. In Python 2 chr will give you a one character string in the ASCII range. This is an 8-bit string, so the maximum parameter value for chris 255. In Python 3 you'll get a unicode character and unicode code points can go up to much higher values.

The issue is that the character you're converting using chr isn't within the range accepted (range(256)). The value 0x2018 in decimal is 8216.
Check out unichr, and also see chr.

Related

SyntaxError: unexpected EOF while parsing -Python

I am using the concept of priority scheduling to create a program that should take two inputs, number of incoming packets, and the priority string for the incoming packets. For example, for input “4” and “HLHH'', the order of outgoing packets should be ``0 2 1 3''.
When i run the program i keep getting this error:
Input:4 HLHH
Traceback (most recent call last):
File "schedule.py", line 71, in <module>
main()
File "schedule.py", line 62, in main
inputStr=input("Input:")
File "<string>", line 1
4 HLHH
^
SyntaxError: unexpected EOF while parsing
Here is my source code :
import re
#Used to set the priorities for initial buffer
def setPriorityForBuffer(priorityStr,priorityList):
counter=0
outgoingPkt=[]
#Set priority for H first
for i in range(0,3):
if priorityStr[i]=='H':
outgoingPkt.append(priorityList[counter])
counter+=1
else:
outgoingPkt.append('NA')
#Set priority for L next
for i in range(0,3):
if outgoingPkt[i]=='NA':
outgoingPkt[i]=priorityList[counter]
counter+=1
return outgoingPkt
def getPriority(numPackets,priorityStr):
outputStr = " "
outgoingPkt=[]
priorityList=[]
for i in range(0,numPackets):
priorityList.append(str(i))
if numPackets<=0:
return 'Wrong input: the number of packets must be greater than 0.'
elif numPackets!=len(priorityStr):
return 'Wrong input: the number of packets is wrong.'
else:
pattern = re.compile('^[LH]+$')
if not re.search(pattern, priorityStr):
return 'Wrong input: the priority must be H or L'
if numPackets==3:
outgoingPkt=setPriorityForBuffer(priorityStr,priorityList)
elif numPackets>3:
#For first 3 packets
outgoingPkt=setPriorityForBuffer(priorityStr,priorityList)
#For remaining packets
counter=3
#Set priority for H first
for i in range(3,len(priorityStr)):
if priorityStr[i]=='H':
outgoingPkt.append(priorityList[counter])
counter+=1
else:
outgoingPkt.append('NA')
#Set priority for L next
for i in range(3,len(priorityStr)):
if outgoingPkt[i]=='NA':
outgoingPkt[i]=priorityList[counter]
counter+=1
for i in outgoingPkt:
outputStr=outputStr+i+" "
return outputStr
def main():
#Get input from user
inputStr=input("Input:")
inputList=inputStr.split(" ")
numPackets=int(inputList[0])
priorityStr=inputList[1]
#Call function and print outgoingpacket string
print("Output:",getPriority(numPackets,priorityStr))
#Driver code
main()
any help is appreciated thanks

Showing "TypeError: unhashable type: 'list'" while using it in nltk.FreqDist() function

I am trying to get the frequency distribution of the word in a phrase according to its degree using nltk. It is showing "TypeError: unhashable type: 'list'" though. Don't understand what the problem is. Please help.
P.S: The code has a whole lot of bugs so don't mind that. I am trying to build a keyword extractor using code snippets from many many programs as I am a noob to python. If anyone wants to shed some light on the other bugs are also welcome.
Code:
from __future__ import division
import operator
import nltk
import string
def isPunct(word):
return len(word) == 1 and word in string.punctuation
def isNumeric(word):
try:
float(word) if '.' in word else int(word)
return True
except ValueError:
return False
class KeyExt:
def __init__(self):
self.stopwords = set(nltk.corpus.stopwords.words())
self.top_fraction = 1
def _generate_candidate_keywords(self, sentences):
phrase_list = []
for sentence in sentences:
words = map(lambda x: "|" if x in self.stopwords else x, nltk.word_tokenize(sentence.lower()))
phrase = []
for word in words:
if word == "|" or isPunct(word):
if len(phrase) > 0:
phrase_list.append(phrase)
phrase = []
else:
phrase.append(word)
return phrase_list
def _calculate_word_scores(self, phrase_list):
word_freq = nltk.FreqDist()
word_degree = nltk.FreqDist()
for phrase in phrase_list:
degree = [x for x in phrase if not isNumeric(x)]
for word in phrase:
word_freq[word]=word_freq[word]+1
word_degree[word, degree]=word_degree[word, degree]+1
for word in word_freq.keys():
word_degree[word] = word_degree[word] + word_freq[word]
word_scores = {}
for word in word_freq.keys():
word_scores[word] = word_degree[word] / word_freq[word]
return word_scores
def _calculate_phrase_scores(self, phrase_list, word_scores):
phrase_scores = {}
for phrase in phrase_list:
phrase_score = 0
for word in phrase:
phrase_score += word_scores[word]
phrase_scores[" ".join(phrase)] = phrase_score
return phrase_scores
def extract(self, text, incl_scores=False):
sentences = nltk.sent_tokenize(text)
phrase_list = self._generate_candidate_keywords(sentences)
word_scores = self._calculate_word_scores(phrase_list)
phrase_scores = self._calculate_phrase_scores(phrase_list, word_scores)
sorted_phrase_scores = sorted(phrase_scores.items(), key=operator.itemgetter(1), reverse=True)
n_phrases = len(sorted_phrase_scores)
if incl_scores:
return sorted_phrase_scores[0:int(n_phrases/self.top_fraction)]
else:
return map(lambda x: x[0],
sorted_phrase_scores[0:int(n_phrases/self.top_fraction)])
def test():
search=input("Enter Text: ")
ke = KeyExt()
keywords = ke.extract(search, incl_scores=True)
print (keywords)
if __name__ == "__main__":
test()
Full Traceback:
Traceback (most recent call last): File "C:\Users\SAURAV
DAS\AppData\Local\Programs\Python\Python35\projects\nlpproj.py", line
81, in <module>
test() File "C:\Users\SAURAV DAS\AppData\Local\Programs\Python\Python35\projects\nlpproj.py", line
77, in test
keywords = ke.extract(search, incl_scores=True) File "C:\Users\SAURAV
DAS\AppData\Local\Programs\Python\Python35\projects\nlpproj.py", line
64, in extract
word_scores = self._calculate_word_scores(phrase_list) File "C:\Users\SAURAV
DAS\AppData\Local\Programs\Python\Python35\projects\nlpproj.py", line
44, in _calculate_word_scores
word_degree[word, degree]=word_degree[word, degree]+1 TypeError: unhashable type: 'list'
This error occurs when you are trying to use a list as a dict key. lists are not hashable and can't be used for keys (e.g. tuples can be used).
In your case in this line
word_degree[word, degree]=word_degree[word, degree]+1
you are using degree as an index for word_degree that doesn't make sense cause degree itself is a list.

the result printed to screen and writen to file are different

# coding=utf-8
def compare(arr1, arr2):
arr1 = arr1.strip()
arr2 = arr2.strip()
arr1 = arr1.split('\t')
arr2 = arr2.split('\t')
# print arr1[0], arr1[1]
arr1min = min(long(arr1[0]), long(arr1[1]))
arr1max = max(long(arr1[0]), long(arr1[1]))
arr2min = min(long(arr2[0]), long(arr2[1]))
arr2max = max(long(arr2[0]), long(arr2[1]))
# print arr1max, arr2max, arr1min, arr1min
if (arr1min < arr2min):
return -1
elif (arr1min > arr2min):
return 1
else:
if (arr1max < arr2max):
return -1
elif (arr1max > arr2max):
return 1
else:
return 0
f = open('er1000000new.txt')
fwrite = open('erzhesorted.txt', 'w')
lines = f.readlines()
lines.sort(compare)
for line in lines:
# fwrite.write(str(line))
print line
f.close()
fwrite.close()
the compare is custom sort function.
for example, when the result printed on screen, the result is
752555452697747457\t752551879448547328\t1468258301659\n
752563934733873152\t752561055289577472\t1468260508664\n
but the result printed on file is
6782762\t12\t1468248110665\n
2660899225\t12\t1468229395665\n
The two results are different, why?
The wb option when you open a file, makes python waiting for a byte object to write in that file.
Your (commented) line fwrite.write(str(line)) sends a string object.
Doesn't it produce the following error?
TypeError: a bytes-like object is required, not 'str'
Also it may come from your compare attribute in sort method.
What is it?
→ Removing the b option and removing the compare attribute produces the same outputs in term and file outputs.

Binary search coming to error in tkinter gui python 2.7

This code is appearing to give me an error to my arguments i don't know what i have done wrong in this code. When attempting to run a binary search inside tkinter using python 2.7 The programs works fine if i don't use the gui just line code. This is the code I have based my program on
http://www.pythonschool.net/data-structures-algorithms/binary-search/
The error is: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python27\lib\lib-tk\Tkinter.py", line 1536, in call return self.func(*args) TypeError: binarySearch() takes exactly 2 arguments (0 given)
from Tkinter import *
import csv
with open('scoresRecord.csv', 'rb') as f:
reader = csv.reader(f)
your_list = list(reader)
root = Tk()
root.resizable(0,0)
root.title("Score Board")
def binarySearch(myitem,myList):
found = False
bottom = 0
top = len(myList)-1
while bottom<=top and not found:
middle = (bottom+top)//2
if myList[middle]== myitem:
found = True
elif myList[middle] < myitem:
bottom = middle + 1
else:
top = middle-1
return found
if __name__=="__main__":
Scorelist = [row[0] for row in your_list]
Dismissallist =[row[1] for row in your_list] # create a list of only the dismissal
Venuelist =[row[2] for row in your_list] # create a list of only the venue
item = int(input(entScore.get()))
Scorelist = map(int, Scorelist)
rowPos = Scorelist.index(item)
isitFound = binarySearch(item,Scorelist)
if isitFound:
Score= Scorelist[rowPos]
Dismissal= Dismissallist[rowPos]
Venue= Venuelist[rowPos]
else:
Score= ("Not Found")
Dismissal= ("Not Found")
Venue= ("Not Found")
numScoreLbl.configure(text=Score)
numDismissal.configure(text=Dismissal)
outVenue.configure(text=Venue)
#==========GUI Section==================#
First of all, make sure your list is ordered, otherwise the results may be wrong.
Second, do this
Scorelist = list(map(int, Scorelist))#convert to list
isitFound = binarySearch(item,Scorelist)
Although, if you are using .index method, then you can do something like this for better performance:
try:
index = Scorelist.index(item)
isitFound = True
except ValueError:
isitFound = False
It takes out the binary search part, but you were using .index anyways. So this is better. Hope it helps :)

Error always on line 102 of my code

So I am creating a module, and I am importing it to a python shell and running some stuff to make sure all features work and such.
For some reason every time I run the code, it gives the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
#anything can be here
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
So where the #anything can be here is, is whatever is on line 102 of my code. Originally line 102 was:
if isinstance(startindex,datetime.datetime):
and I got the error above. I put a quick print statement on line 102 to check and it gave the same error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
print 'Hello'
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
Is this some sort of bug? Why is it telling me there is an error with datetime on the line print 'Hello'?
Because it may be helpful, I will give you the function I am having trouble with since I have no clue how this is possible. I am keeping the print 'Hello' line so you can see where line 102 is:
def url_maker(latitudes,longitudes,times=None,color='red',label=' ',zoom=12,center=None,start=None,end=None,by=None,size='600x300'):
urls = []
import datetime
if isinstance(times[0],str) or isinstance(times[0],datetime.datetime):
from dateutil import parser
if isinstance(times[0],str):
times = [parser.parse(x) for x in times]
if isinstance(start,str):
startindex = parser.parse(start)
else:
startindex = start
if isinstance(end,str):
endindex = parse.parse(end)
else:
endindex = end
print 'Hello'
if isinstance(startindex,datetime.datetime):
startpos = between_times(times,startindex,by='start')
elif isinstance(startindex,int):
if isinstance(endindex,datetime.datetime):
startpos = between_times(times,endindex,by='end') - start
else:
startpos = start
else:
pass
if isinstance(endindex,datetime.datetime):
endpos = between_times(times,endindex,by='end')
elif isinstance(endindex,int):
if isinstance(startindex,datetime.datetime):
endpos = between_times(times,startindex,by='start') + end
else:
endpos = end
else:
pass
else:
times = range(1,len(latitudes) + 1)
if isinstance(start,int):
startpos = start
else:
startpos = None
if isinstance(end,int):
endpos = end
else:
endpos = None
if isinstance(by,str):
lat,lon,t = latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print lat
t,lats,lons = time_sample(t,by,lat,lon)
elif isinstance(by,int):
lats,lons,t = latitudes[startpos:endpos:by],latitudes[startpos:endpos:by],times[startpos:endpos:by]
else:
lats,lons,t= latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print t
print len(t)
if center == None:
latit = [str(i) for i in lats]
longi = [str(i) for i in lons]
center = '&center=' + common_finder(latit,longi)
else:
center = '&center=' + '+'.join(center.split())
zoom = '&zoom=' + str(zoom)
for i in range(len(lats)):
#label = str(i)
x,y = str(lats[i]),str(lons[i])
marker = '&markers=color:' + color + '%7Clabel:' + label + '%7C' + x + ',' + y
url = 'http://maps.googleapis.com/maps/api/staticmap?maptype=roadmap&size=' + size + zoom + center + marker + '&sensor=true'
urls.append(url)
#print i
return urls,t
You are running with a stale bytecode cache or are re-running the code in an existing interpreter without restarting it.
The traceback code has only bytecode to work with, which contains filename and linenumber information. When an exception occurs, the source file is loaded to retrieve the original line of code, but if the source file has changed, that leads to the wrong line being shown.
Restart the interpreter and/or remove all *.pyc files; the latter will be recreated when the interpreter imports the code again.
As for your specific exception; you probably imported the datetime class from the datetime module somewhere:
from datetime import datetime
The datetime class does not have a datetime attribute, only the module does.

Categories

Resources