Im trying to download a picture from the internet but once I use string formatting it gives me an Error:
"UnicodeEncodeError: 'ascii' codec can't encode character '\xdf' in position 161: ordinal not in range(128)"
If I remove string formatting the picture is downloadable.
I have already tried to encode and decode but nothings works.
def get_location(self):
self.key = self.key_entry.get()
self.location = self.location_entry.get()
self.zoom = self.zoom_entry.get()
self.type = self.type_entry.get()
self.url = "https://www.mapquestapi.com/staticmap/v4/getplacemap?key=%s&size=600,600&type=%s&imagetype=png&zoom=%s&scalebar=false&traffic=false&location=%s" % (self.key, self.type, self.zoom, self.location)
webbrowser.open_new_tab('%s' % self.url)
urllib.request.urlretrieve(self.url, "location.png")
try using utf-8
webbrowser.open_new_tab('%s' % self.url, 'utf-8')
Related
red_voznje = []
def otvori_redvoznje(prevoznik,odrediste,peron,rezervacija,termin):
datoteka = open("red_voznje.csv","r",encoding="utf-8")
for line in datoteka:
vrednosti = line.rstrip().rsplit(",")
recnik = {
"prevoznik": vrednosti[0],
"odrediste": int(vrednosti[1]),
"peron": int(vrednosti[2]),
"rezervacija": vrednosti[3],
"termin": int(vrednosti[4])
}
red_voznje.append(recnik)
return red_voznje
Here is the error i get:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
could avoid unicode error with errors = 'ignore' in open()
eg datoteka = open("red_voznje.csv","r",encoding="utf-8", errors="ignore")
I have the string 'Leicht bewölkt'.
The 'ö' is causing the error
'ascii' codec can't encode character u'\xf6' in position 10: ordinal not in range(128)
I tried to encode it into utf8 # - *- coding: utf- 8 - *- to the start if the file but it does not work. Could you help me out with that? I just want to print it into the command line and send it to an arduino.
def removeThat(schasch):
print(schasch)
schasch = str(schasch).encode('utf8')
schasch = str(schasch).encode('utf8').replace("ü","ue").replace("ä","ae").replace("ö","oe").replace("ß","sss")
return schasch
Replace characters before you encode the string into utf8
replacements = {
'ü': 'ue',
'ä': 'ae',
'ö': 'oe',
'ß': 'ss',
}
def replace_umlauts(text: str) -> str:
for find, replace in replacements.items():
text = text.replace(find, replace)
return text
def encode_text(text: str) -> bytes:
fixed = replace_umlauts(text)
return fixed.encode('utf-8')
if __name__ == '__main__':
text = 'Leicht bewölkt'
print(replace_umlauts(text))
print(encode_text(text))
which prints
Leicht bewoelkt
b'Leicht bewoelkt'
import urllib.request
def read_text():
quotes = open(r"C:\Users\Intel\Google Drive\Udacity\Full Stack\AbdoulCoverLetter.txt")
contents_of_files = quotes.read()
print(contents_of_files)
quotes.close()
check_profanity(contents_of_files)
My code is showing the following error:
UnicodeEncodeError: 'ascii' codec can't encode character '\u2022' in position 154: ordinal not in range(128)
I am not sure what is the issue. Please help..
def check_profanity(text_to_check):
with urllib.request.urlopen("http://www.wdylike.appspot.com/?q="+text_to_check) as response:
connection = response.read()
output = connection.read()
connection.close()
read_text()
I removed the bullet list and I changed the code. It is working fine now. Thanks..
import urllib.request
def read_text():
quotes = open(r"C:\Users\Intel\Google Drive\Udacity\Full Stack\AbdoulCoverLetter.txt")
contents_of_files = quotes.read()
print(contents_of_files)
quotes.close()
check_profanity(contents_of_files)
def check_profanity(text_to_check):
connection = urllib.request.urlopen("http://www.wdylike.appspot.com/?" + urllib.parse.urlencode([('q', text_to_check)]))
output = connection.read()
connection.close()
read_text()
This question already has an answer here:
how to interpret this error "UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 164: ordinal not in range(128)"
(1 answer)
Closed 5 years ago.
I'm writing a script in Python 3.5.3 that takes username/password combos from a file and writes them to another file. The script was written on a machine with Windows 10 and worked. However, when I tried to run the script on a MacBook running Yosemite, I got an error that has something to do with ASCII encoding.
The relevant function is this:
def buildDatabase():
print("Building database, this may take some time...")
passwords = open("10-million-combos.txt", "r") #File with user/pword combos.
hashWords = open("Hashed Combos.txt", "a") #File where user/SHA-256 encrypted pwords will be stored.
j = 0
hashTable = [[ None ] for x in range(60001)] #A hashtable with 30,000 elements, quadratic probing means size must = 2 x the final size + 1
for line in passwords:
toSearch = line
i = q = toSearch.find("\t") #The username/pword combos are formatted: username\tpassword\n.
n = toSearch.find("\n")
password = line[i:n-1] #i is the start of the password, n is the end of it
username = toSearch[ :q] + ":" #q is the end of the username
byteWord = password.encode('UTF-8')
sha.update(byteWord)
toWrite = sha.hexdigest() #password is encrypted to UTF-8, run thru SHA-256, and stored in toWrite
skip = False
if len(password) == 0: #if le(password) is 0, just skip it
skip = True
if len(password) == 1:
doModulo = ord(password[0]) ** 4
if len(password) == 2:
doModulo = ord(password[0]) * ord(password[0]) * ord(password[1]) * ord(password[1])
if len(password) == 3:
doModulo = ord(password[0]) * ord(password[0]) * ord(password[1]) * ord(password[2])
if len(password) > 3:
doModulo = ord(password[0]) * ord(password[1]) * ord(password[2]) * ord(password[3])
assignment = doModulo % 60001
#The if block above gives each combo an assignment number for a hash table, indexed by password because they're more unique than usernames
successful = False
collision = 0
The error is as follows:
Traceback (most recent call last):
File "/Users/connerboehm/Documents/Conner B/PythonFinalProject.py", line 104, in <module>
buildDatabase()
File "/Users/connerboehm/Documents/Conner B/PythonFinalProject.py", line 12, in buildDatabase
for line in passwords:
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xaa in position 2370: ordinal not in range(128)
What's happening here? I haven't gotten this error before on Windows, and I can't see any problem with my attempt to encode into UTF-8.
Edit: Notepad encodes in ANSI. Changing the encoding (just copying and pasting the data to a new .txt file) to UTF-8 solved the problem.
Your program doesn't say what codec is used in the file "10-million-combos.txt", so Python is in this case trying to decode it as ASCII. 0xaa isn't an ASCII ordinal so that failed. Identify what codec is used in your file and pass that in the encoding parameter for open.
i want drawing the russian text in pysfml, but i get error.
#!/usr/bin/python
# -*- encoding: utf-8 -*-
import sfml as sf
import json
class draws:
def __init__(self):
with open('setting.json') as data_file:
setting = json.load(data_file)
print
self.window = sf.RenderWindow(sf.VideoMode(setting['window_width'],
setting['window_height']),
setting['title'])
self.run()#bot
def run(self):
font = sf.Font.from_file("arial.ttf")
text = sf.Text("Русский текст", font, 16)#this error string
while self.window.is_open:
for event in self.window.events:
if type(event) is sf.CloseEvent:
self.window.close()
self.window.clear(sf.Color.BLUE)
self.window.draw(text)
self.window.display()
if __name__ == "__main__":
Tree = draws()
Console error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal
not in range(128)
I use unicode:
text = sf.Text(u"Русский текст", font, 16)#this error string
exelent, but wrong drawing literals.
image error
I use cp1253(russian codec)
text = sf.Text(u"Русский текст".encode('cp1253'), font, 16)
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-6: cha
racter maps to
text = sf.Text(u"Русский текст".decode('cp1253'), font, 16)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-6: ordin
al not in range(128)
English text exelent draw.
I now not see as this job.