EDIT: UPDATE, so I ran this with #Alex Thornton's suggestion.
This is my output:
'100.00"\r'
Traceback (most recent call last):
File "budget.py", line 48, in <module>
Main()
File "budget.py", line 44, in Main
budget = readBudget("budget.txt")
File "budget.py", line 21, in readBudget
p_value = float(maxamount)
ValueError: invalid literal for float(): 100.00"
Under Windows though, I just get the list of numbers, with the qutations and the \r's stripped off.
Now, I don't know too much about the way Windows and Linux handle text files, but isn't it due to the way Windows and Linux handle the return/enter key?
So I have this code:
def readBudget(budgetFile):
# Read the file into list lines
f = open(budgetFile)
lines = f.readlines()
f.close()
budget = []
# Parse the lines
for i in range(len(lines)):
list = lines[i].split(",")
exptype = list[0].strip('" \n')
if exptype == "Type":
continue
maxamount = list[1].strip('$" \n')
entry = {'exptype':exptype, 'maxamnt':float(maxamount)}
budget.append(entry)
#print(budget)
return budget
def printBudget(budget):
print()
print("================= BUDGET ==================")
print("Type".ljust(12), "Max Amount".ljust(12))
total = 0
for b in budget:
print(b['exptype'].ljust(12), str("$%0.2f" %b['maxamnt']).ljust(50))
total = total + b['maxamnt']
print("Total: ", "$%0.2f" % total)
def Main():
budget = readBudget("budget.txt")
printBudget(budget)
if __name__ == '__main__':
Main()
Which reads from this file:
"Type", "MaxAmount"
"SCHOOL","$100.00"
"UTILITIES","$200.00"
"AUTO", "$100.00"
"RENT", "$600.00"
"MEALS", "$300.00"
"RECREATION", "$100.00"
It is supposed to extract the budget type (school, utilities, etc) and the max amount. The max amount is supposed to be converted to a float. However, when I run the program, I get this error.
Traceback (most recent call last):
File "budget.py", line 47, in <module>
Main()
File "budget.py", line 43, in Main
budget = readBudget("budget.txt")
File "budget.py", line 22, in readBudget
entry = {'exptype':exptype, 'maxamnt':float(maxamount)}
ValueError: invalid literal for float(): 100.00"
Shouldn't the strip function in readBudget remove the last quotation mark?
When I tried this:
>>> attempt = '"$100.00"'
>>> new = attempt.strip('$" \n')
'100.00'
>>> float(new)
100.00
I got exactly what one would expect- so it must be something to do with what we cannot see from the file. From what you've posted, it's not clear whether there is something subtly wrong with the string you're trying to pass to float() (because it looks perfectly reasonable). Try adding a debug print statement:
print(repr(maxamount))
p_value = float(maxamount)
Then you can determine exactly what is being passed to float(). The call to repr() will make even normally invisible characters visible. Add the result to your question and we will be able to comment further.
EDIT:
In which case, replace:
maxamount = list[1].strip('$" \n')
With:
maxamount = list[1].strip('$" \n\r')
That should then work fine.
Adding in this:
maxamount = list[1].strip('$" \n\r')
Or more specifically, the \r, removed the error.
You can use a regex to capture either all or most of the floating point info in a string.
Consider:
import re
valid='''\
123.45"
123.
123"
.123
123e-16
-123e16
123e45
+123.45'''
invalid='''\
12"34
12f45
e123'''
pat=r'(?:^|\s)([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)'
for e in [valid, invalid]:
print
for line in e.splitlines():
m=re.search(pat, line)
if m:
print '"{}" -> {} -> {}'.format(line, m.group(1), float(m.group(1)))
else:
print '"{}" not valid'.format(line)
Prints:
"123.45"" -> 123.45 -> 123.45
"123." -> 123 -> 123.0
"123"" -> 123 -> 123.0
".123" -> .123 -> 0.123
"123e-16" -> 123e-16 -> 1.23e-14
"-123e16" -> -123e16 -> -1.23e+18
"123e45" -> 123e45 -> 1.23e+47
"+123.45" -> +123.45 -> 123.45
"12"34" -> 12 -> 12.0
"12f45" -> 12 -> 12.0
"e123" not valid
Just modify the regex to capture what you consider a valid floating point data point -- or invalid.
Related
Im new to python and coding and im trying to understand how re.search and indexing works.
below is what I have so far and I want physical_state to equal what comes after the Completion: (in this case it is success) but I dont really understand how the match.group(1) and re.search works.
import ops # Import the OPS module.
import sys # Import the sys module.
import re
# Subscription processing function
def ops_condition (o):
status, err_str = o.timer.relative("tag",10)
return status
def ops_execute (o):
handle, err_desp = o.cli.open()
print("OPS opens the process of command:",err_desp)
result, n11, n21 = o.cli.execute(handle,"return")
result, n11, n21 = o.cli.execute(handle,"dis nqa results test-instance sla 1 | i Completion:")
match = re.search(r"Completion:", result)
if not match:
print("Could not determine the state.")
return 0 # Look into what the return values mean.
physical_state = match.group(1) # Gets the first group from the match.
print (physical_state)
result = o.cli.close(handle)
return 0
output of result, n11, n21 = o.cli.execute(handle,"dis nqa results test-instance sla 1 | i Completion:")
Completion:success RTD OverThresholds number: 0
Completion:success RTD OverThresholds number: 0
Completion:success RTD OverThresholds number: 0
Completion:success RTD OverThresholds number: 0
Completion:success RTD OverThresholds number: 0
error when run
<setup>('OPS opens the process of command:', 'success')
Oct 18 2018 06:12:57+00:00 setup %%01OPSA/3/OPS_RESULT_EXCEPTION(l)[410]:Script is test3.py, current event is tag, instance is 1381216156, exception reason is Traceback (most recent call last):
File ".lib/frame.py", line 114, in <module>
ret = m.ops_execute(o)
File "flash:$_user/test3.py", line 21, in ops_execute
physical_state = match.group(1) # Gets the first group from the match.
IndexError: no such group
Thanks in advance
First of, i'm sort of new to Python so sorry if this question is obvious. The detect english module appears to be wrong, but it functions perfectly fine when calling it and running it on its own, theres no errors when running it alone and i've rewritten it a couple times to triple check it.
Traceback (most recent call last):
File "H:\Python\Python Cipher Program\transposition hacker.py", line 49, in <module>
main()
File "H:\Python\Python Cipher Program\transposition hacker.py", line 11, in main
hackedMessage = hackTransposition(myMessage)
File "H:\Python\Python Cipher Program\transposition hacker.py", line 34, in hackTransposition
if detectEnglish.isEnglish(decryptedText):
File "H:\Python\Python Cipher Program\detectEnglish.py", line 48, in isEnglish
wordsMatch = getEnglishCount(message) * 100 >= wordPercentage
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
this is the error i am getting when trying to run the Transposition Hacker (copied directly from here
Here is the code for the Detect English Module
# Detect english Module
# to use this code
# import detectEnglish
# detectEnglish.isEnglish(somestring)
# returns true of false
# there must be a dictionary.txt file in the same directory
# all english words
# one per line
UPPERLETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + ' \t\n'
def loadDictionary()
dictionaryFile = open('Dictionary.txt')
englishWords = {}
for word in dictionaryFile.read().split('\n'):
englishWords[word] = None
dictionaryFile.close()
return englishWords
ENGLISH_WORDS = loadDictionary()
def getEnglishCount(message):
message = message.upper()
message = removeNonLetters(message)
possibleWords = message.split()
if possibleWords == []:
return 0.0
matches = 0
for word in possibleWords:
if word in ENGLISH_WORDS:
matches += 1
return float(matches) / len(possibleWords)
def removeNonLetters(message):
lettersOnly = []
for symbol in message:
if symbol in LETTERS_AND_SPACE:
lettersOnly.append(symbol)
return ''.join(lettersOnly)
def isEnglish(message, wordPercentage=20, letterPercentage=85):
# by default 20% of the words mustr exist in dictionary file
# 85% of charecters in messafe must be spaces or letters
wordsMatch = getEnglishCount(message) * 100 >= wordPercentage
numLetters = len(removeNonLetters(message))
messageLettersPercentage = float(numLetters) / len(message) * 100
lettersMatch = messageLettersPercentage >= letterPercentage
return wordsMatch and lettersMatcht
getEnglishCount looks like it is missing a return statement. If python gets to the end of a function without hitting a return statement it will return None as you're seeing.
try this:
def getEnglishCount(message):
message = message.upper()
message = removeNonLetters(message)
possibleWords = message.split()
# if possibleWords == []: # redundant
# return 0.0
return len(possibleWords)
Edit: #Kevin Yea I think you're right - there was more in that function. Maybe try this:
def getEnglishCount(message):
message = message.upper()
message = removeNonLetters(message)
possibleWords = message.split()
if possibleWords == []:
return 0.0
matches = 0.
for word in possibleWords:
if word in ENGLISH_WORDS:
matches += 1
return matches / len(possibleWords)
I'd guess the indentation somehow got changed when you copy and pasted the code, with the return statement nested under the if.
As the other poster has said, you're missing a return for the getEnglishCount method, so it's returning NoneType, meaning that there is no value to be returned.
You can't do math on NoneTypes, so the NoneType*100 fails, which is what the bottom of your error traceback says.
from PIL import Image
import input_class
import input_function
import input_crop_values
import input_translate
class ImageChanger():
def __init__ ():
image_filename = input_class.input_file_name()
self.my_image = Image.open(image_filename)
chosen_Function = input_function.input_vaild_function()
if chosen_Function == "Crop" or chosen_Function == "crop":
crop_values = input_crop_values.input_crop_data()
my_image.crop(crop_values)
elif chosen_Function == "Translate" or chosen_function == "translate":
translate_values = input_translate.input_translate_data()
my_image.crop(translate_values)
else:
print("unexpected error while running code")
def printState():
print( "Your image file name is %s" % self.my_filename );
return (self.my_filename);
def translate(self,x_cord,y_cord):
return (self.my_image.offset(x_cord,y_cord));
def crop(self, box):
return (self.my_image.crop(box))
sorry for odd formatting,
Error:
Traceback (most recent call last):
File "C:\Users\Alexander\Desktop\Final_Udacity_project\dragon_picture_test.py", line 1, in <module>
import picture_changer
File "C:\Users\Alexander\Desktop\Final_Udacity_project\picture_changer.py", line 3, in <module>
import input_function
File "C:\Users\Alexander\Desktop\Final_Udacity_project\input_function.py", line 14
else
^
SyntaxError: invalid syntax
I have some other functions, not listed that use the input command sort of like a user interface, then it returns it to the larger class.
The places that the values are returned and what is return is:
line 8*: image_filename = input_class.input_file_name() # you would give a name of a picture here,
line 10*: chosen_function = input_function.input_vaild_function() # you Would give it either crop or translate can be sentence case or lowercase
line 11*: crop_values = input_crop_values.input_crop_data() # you would give it data in brackets like [1,2,3,4] and it would crop it.
line 15*: translate_values = input_translate.input_translate_data() # you would give it information in ( ), like (1,2,3,4) and it would translate it.
The code is acting really weird with the Boolean and the error message isn't helping me that much.
else, like other statements that come before a block, requires a colon.
else:
I was making a site component scanner with Python. Unfortunately, something goes wrong when I added another value to my script. This is my script:
#!/usr/bin/python
import sys
import urllib2
import re
import time
import httplib
import random
# Color Console
W = '\033[0m' # white (default)
R = '\033[31m' # red
G = '\033[1;32m' # green bold
O = '\033[33m' # orange
B = '\033[34m' # blue
P = '\033[35m' # purple
C = '\033[36m' # cyan
GR = '\033[37m' # gray
#Bad HTTP Responses
BAD_RESP = [400,401,404]
def main(path):
print "[+] Testing:",host.split("/",1)[1]+path
try:
h = httplib.HTTP(host.split("/",1)[0])
h.putrequest("HEAD", "/"+host.split("/",1)[1]+path)
h.putheader("Host", host.split("/",1)[0])
h.endheaders()
resp, reason, headers = h.getreply()
return resp, reason, headers.get("Server")
except(), msg:
print "Error Occurred:",msg
pass
def timer():
now = time.localtime(time.time())
return time.asctime(now)
def slowprint(s):
for c in s + '\n':
sys.stdout.write(c)
sys.stdout.flush() # defeat buffering
time.sleep(8./90)
print G+"\n\t Whats My Site Component Scanner"
coms = { "index.php?option=com_artforms" : "com_artforms" + "link1","index.php?option=com_fabrik" : "com_fabrik" + "ink"}
if len(sys.argv) != 2:
print "\nUsage: python jx.py <site>"
print "Example: python jx.py www.site.com/\n"
sys.exit(1)
host = sys.argv[1].replace("http://","").rsplit("/",1)[0]
if host[-1] != "/":
host = host+"/"
print "\n[+] Site:",host
print "[+] Loaded:",len(coms)
print "\n[+] Scanning Components\n"
for com,nme,expl in coms.items():
resp,reason,server = main(com)
if resp not in BAD_RESP:
print ""
print G+"\t[+] Result:",resp, reason
print G+"\t[+] Com:",nme
print G+"\t[+] Link:",expl
print W
else:
print ""
print R+"\t[-] Result:",resp, reason
print W
print "\n[-] Done\n"
And this is the error message that comes up:
Traceback (most recent call last):
File "jscan.py", line 69, in <module>
for com,nme,expl in xpls.items():
ValueError: need more than 2 values to unpack
I already tried changing the 2 value into 3 or 1, but it doesn't seem to work.
xpls.items returns a tuple of two items, you're trying to unpack it into three. You initialize the dict yourself with two pairs of key:value:
coms = { "index.php?option=com_artforms" : "com_artforms" + "link1","index.php?option=com_fabrik" : "com_fabrik" + "ink"}
besides, the traceback seems to be from another script - the dict is called xpls there, and coms in the code you posted...
you can try
for (xpl, poc) in xpls.items():
...
...
because dict.items will return you tuple with 2 values.
You have all the information you need. As with any bug, the best place to start is the traceback. Let's:
for com,poc,expl in xpls.items():
ValueError: need more than 2 values to unpack
Python throws ValueError when a given object is of correct type but has an incorrect value. In this case, this tells us that xpls.items is an iterable an thus can be unpacked, but the attempt failed.
The description of the exception narrows down the problem: xpls has 2 items, but more were required. By looking at the quoted line, we can see that "more" is 3.
In short: xpls was supposed to have 3 items, but has 2.
Note that I never read the rest of the code. Debugging this was possible using only those 2 lines.
Learning to read tracebacks is vital. When you encounter an error such as this one again, devote at least 10 minutes to try to work with this information. You'll be repayed tenfold for your effort.
As already mentioned, dict.items() returns a tuple with two values. If you use a list of strings as dictionary values instead of a string, which should be split anyways afterwards, you can go with this syntax:
coms = { "index.php?option=com_artforms" : ["com_artforms", "link1"],
"index.php?option=com_fabrik" : ["com_fabrik", "ink"]}
for com, (name, expl) in coms.items():
print com, name, expl
>>> index.php?option=com_artforms com_artforms link1
>>> index.php?option=com_fabrik com_fabrik ink
I'm bukkit jython/python plugin programmer. Last few days, I'm struggling with this problem. I have to add an potion effect to an user, it's not problem if I enter effect name, duration and amplifier manually in code, but when I want to get them from config, I get this error:
13:38:20 [SEVERE] Could not pass event PlayerInteractEvent to ItemEffect v1.0
Traceback (most recent call last):
File "<iostream>", line 126, in onPlayerInteractEvent
TypeError: addPotionEffect(): 1st arg can't be coerced to org.bukkit.potion.Poti
onEffect
Here's that part of code:
effectname = section.getString("%s.effect"%currentKey)
duration = section.getInt("%s.duration"%currentKey)
durationinticks = duration * 20
geteffectname = "PotionEffectType.%s"%effectname
getpotioneffect = "PotionEffect(%s, %i, 1)"%(geteffectname, durationinticks)
geteffectname = "PotionEffectType.%s"%effectname
if iteminhand == currentKey:
event.getPlayer().addPotionEffect(getpotioneffect)
When I print getpotioneffect out, I get:
13:38:20 [INFO] PotionEffect(PotionEffectType.SPEED, 600, 1)
which is okay, and should work. I tested it without getting informations from config, and it works perfectly... To sum up, code above is not working, but below one works:
getpotioneffect = PotionEffect(PotionEffectType.SPEED, 600, 1)
if iteminhand == currentKey:
event.getPlayer().addPotionEffect(getpotioneffect)
Link to javadocs of this event!
http://jd.bukkit.org/rb/apidocs/org/bukkit/entity/LivingEntity.html#addPotionEffect(org.bukkit.potion.PotionEffect)
Thanks!
In your first snippet, getpotioneffect is a string. You can check it adding print type(getpotioneffect) somewhere.
What you want is to replace this :
geteffectname = "PotionEffectType.%s"%effectname
getpotioneffect = "PotionEffect(%s, %i, 1)"%(geteffectname, durationinticks)
with this:
effect_type = getattr(PotionEffectType, effectname)
potion_effect = PotionEffect(effect_type, durationinticks, 1)