replace values in a float with a string- python - python

I wanted to replace dot in a float with a string
for example if I have a float 15.444 I need print it something like below 15 eggs 444 chicken
If take I take a real example,here is the code
enter code here
name = "chris"
height_cm = 175
height = (height_cm * 1/2.54) * 1/12
weight = 79
print "He is %s" % name
print "His height is %.2f" %height, "inches"
print "His weight is %d" % weight
the second print line will give the output "my height is 5.7 inches" here how do I replace "." with a string. In this case I need to replace the "." with a string "feet"
++++++++++++++++++output++++++++++++++++++++++++
He is chris
His height is 5.7 inches
His weight is 79
+++++++++++++++++++output+++++++++++++++++++++++

I don't code python but you may want to do something along the line of this(java):
float input = 15.444f;
int[] split = (input+"").split(".");
System.out.println(split[0]+" eggs and "+split[1]+" chickens");
But why would you ever need to do something like this. A float is a horrible method of storage for 2 integer values. Try using an array instead.

Related

Parameters feeding input variables in Python

Beginning Python guy here. Have some code I need help with.
My main question here is in this bit of code we have 3 define statements for mm, yy, and yyyy.
In the 'hpds_folder =' statement it references 'dnb*{0}{1}' with the {0} and {1} being the 1st and 2nd input parameters.
mm = hadoop.date_part()['mm']
yy = hadoop.date_part()['yy']
yyyy = hadoop.date_part()['yyyy']
hdfs_folder = '/sandbox/US_MARKETING/COMMON_DATA/BAU/FILES/{0}/{1}'.format(yyyy, mm)
find_dnb = hadoop.file_find(file='dnb*{0}*{1}*'.format(mm, yy), folder = hadoop._xfer_in_hadoop['dnb'])
print('dnb*{0}*{1}*')
I'm assuming {0} and {1} should be what are populated by mm and yy respectively.
But when I try to print out the string for it:
print('dnb*{0}{1}')
I get just the literal 'dnb*{0}{1}' as output.
Shouldn't I get a month and a year?
On your print statement, you didn't format the text, so it wasn't replaced. the assignment on file happened once and didn't change the string literal for other locations.
Therefore, your print should be formatted as well:
print('dnb*{0}*{1}*'.format(mm, yy))
In Python3.6+, a new formatted strings were introduced, letting you do things such as:
print(f'dnb*{mm}*{yy}*')
Notice the f before the string mark. fstrings let you inject code to the string inside curly brackets {}.
You can also use it on your find_dnb line:
find_dnb = hadoop.file_find(file=f'dnb*{mm}*{yy}*', folder = hadoop._xfer_in_hadoop['dnb'])

How can I extract a floating point value from a string, in python 3?

string = probability is 0.05
how can I extract 0.05 float value in a variable? There are many such strings in the file,I need to find the average probability, so
I used 'for' loop.
my code :
fname = input("enter file name: ")
fh = open(fname)
count = 0
val = 0
for lx in fh:
if lx.startswith("probability"):
count = count + 1
val = val + #here i need to get the only "float" value which is in string
print(val)
import re
string='probability is 1'
string2='probability is 1.03'
def FindProb(string):
pattern=re.compile('[0-9]')
result=pattern.search(string)
result=result.span()[0]
prob=string[result:]
return(prob)
print(FindProb(string2))
Ok, so.
This is using the regular expression (aka Regex aka re) library
It basically sets up a pattern and then searches for it in a string.
This function takes in a string and finds the first number in the string, then returns the variable prob which would be the string from the first number to the end.
If you need to find the probability multiple times then this might do it:
import re
string='probability is 1'
string2='probability is 1.03 blah blah bllah probablity is 0.2 ugggggggggggggggg probablity is 1.0'
def FindProb(string):
amount=string.count('.')
prob=0
for i in range(amount):
pattern=re.compile('[0-9]+[.][0-9]+')
result=pattern.search(string)
start=result.span()[0]
end=result.span()[1]
prob+=float(string[start:end])
string=string[end:]
return(prob)
print(FindProb(string2))
The caveat to this is that everything has to have a period so 1 would have to be 1.0 but that shouldn't be too much of a problem. If it is, let me know and I will try to find a way

Python_ Taking multiple inputs of different data type in one line

I wish to take in two inputs from the user in one line, a score (in integer) and a name (in string) in one line, separated by a blank space.
So for example, an input may be 90 Amy.
I don't want to store both as string and then convert one later; I want to store one as an integer and one as a string from the start.
I have tried some codes but they are not working and I'm struggling.
score, name = (int(input()), input()).split()
print(score)
print(name)
It is one line solution, but not efficient:
x, y = [int(x) if x.isdigit() else x for x in input("Enter two value: ").split()]
Convert input to array and check if all elements digit or not. This is how it works.
Try this if you have no problem with 2 line:
x, y = input("Enter a two value: ").split()
x = int(x)
If you want to read only one line from the console (ie one input) you may not to try non-intuitive thing, just use two lines and do
result = input().split()
score, name = int(result[0]), result[1]
If you're ok to read 2 lines, (ie 2 input)
score, name = int(input('Score: ')), input('Name: ')
You can do it like this
score, name = int(input('Enter Score: ')), input('Enter name:')
print(score)
print(name)

save print value into a text file python

I have this 2 program:
def calculate1():
a4canon = (int(input('A4 paper (canon):')))*8.9
a4rainbow = (int(input('A4 paper (rainbow):')))*7.5
lruler = (int(input('Long ruler:')))*0.85
sruler = (int(input('Short ruler:')))*0.55
blue = (int(input('Blue pen:')))*0.65
red = (int(input('Red pen:')))*0.65
black = (int(input('Black pen:')))*0.65
pencil = (int(input('2B Pencil:')))*2.4
total = a4canon + a4rainbow + lruler + sruler + blue + red + black + pencil
a4canon1 = str(a4canon)
a4rainbow1 = str(a4rainbow)
lruler1 = str(lruler)
sruler1 = str(sruler)
blue1 = str(blue)
red1 = str(red)
black1 = str(black)
pencil1 = str(pencil)
total1 = str(total)
return('A4 paper (canon):',a4canon1)
return('A4 paper (rainbow):',a4rainbow1)
return('Long ruler :',lruler1)
return('Short ruler:',sruler1)
return('Blue pen:',blue1)
return('Red pen:',red1)
return('Black pen:',black1)
return('Pencil:',pencil1)
return('Total:',total1)
and the other:
import calculate
def display1():
file = open('sample.txt','w')
file.write(calculate.calculate1())
display1()
The problem is that it prints:
TypeError: write() argument must be str, not tuple
Am I missing something although I have change the value into string because I want it to save into text file something like this:
A4 paper(canon):1 ~ 8.9
A4 paper(rainbow):1 ~ 7.5
Long ruler:1 ~ 0.85
Short ruler:1 ~ 0.55
Blue pen:1 ~ 0.65
red pen:1 ~ 0.65
Black pen:1 ~ 0.65
2B pencil:1~ 2.4
Total:22.149999999999995
Help and suggestion please. Thanks
it seems that when i use the:
file.write(str(calculate.calculate1()))
it only save:
('A4 paper (canon):', 8.9)
File write will accept strings only that's why you are getting the error. So when you are returning you can return like this
return("A4 paper (canon):" + str(a4canon1)) which will return a string and you can use it for file.write
or while using return value you can convert it to string
file.write(str(calculate.calculate1()))
Also in your definition,you have multiple return statements . Nothing will be executed after first return statement. Remove all your return statements and return a list of string instead of returning multiple strings
return[('A4 paper (canon):',a4canon1),('A4 paper (rainbow):',a4rainbow1),('Long ruler :',lruler1),('Short ruler:',sruler1),('Blue pen:',blue1),('Red pen:',red1),('Black pen:',black1),('Pencil:',pencil1),('Total:',total1)]
And in when capturing return value change like this
import calculate
def display1():
file = open('sample.txt','w')
lst=calculate.calculate1()
for i in lst:
file.write(" ".join(list(i)))
display1()
And also it is not advised to take inputs inside the function definition. You may need to rework on it
File.write accepts string but in your case the it returns a tuple, so instead of writing tuple to file you need to convert it into string by using str() and then write it to file.
You may want to learn more about file operations and also type conversions.
file.write(str(calculate.calculate1()))

re.sub python to gather height

I am writing a python program to parse some user data from a txt file.
One of the rows in the text file will contain the user's height.
I have specified an order that the user is expected to follow like
First line of the file should contain name, the next line, date of birth,
3rd line, height etc.
I have also given a sample file to the user which looks like this
Name: First Name Last Name
DOB: 16.04.2000
Age: 16
Height: 5 feet 9 inch
When I read the file, I looked at each line and split it using ':' as a separator.
The first field is my column name like name, dob, age, height.
In some cases, users forget the ':' after Name or DOB, or they will simply send data like:
Height 5 feet 9 inch
5 feet 9 inch
5ft 9 in
5feet 9inches
The logic I have decided to use is:
Look for ':' on each line; if one is found, then I have my field.
Otherwise, try to find out what data it could be.
The logic for height is like this:
if any(heightword in file_line.upper() for heightword in ['FT', 'HEIGHT', 'FEET', 'INCH', 'CM'])
This if condition will look for words associated with height.
Once I have determined that the line from the file contains the height, I want to be able to convert that information to inches before I write it to the database.
Please can someone help me work out how to convert the following data to inches.
Height 5 feet 9 inch
5 feet 9 inch
5ft 9 in
5feet 9inches
I know since I am trying to cater to variety of user inputs. This list is not exhaustive; I am trying to use these as an example to understand, and then I will keep adding code if and when I find new patterns.
pyparsing is a nice module for simple parsing situations like this, especially when trying to process less-than-predictable-but-still-fairly-structured human input. You can compose your parser using some friendly-named classes (Keyword, Optional, OneOrMore, and so on) and arithmetic operators ('+' for sequence, '|' for alternatives, etc.), to assemble smaller parsers into larger ones. Here is a parser built up from bits for your example (also support ' and " for feet and inches, and fractional feet and inch values too). (This sample uses the latest version of pyparsing, version 2.1.4):
samples = """\
Height 5 feet 9 inch
5 feet 9 inch
5ft 9 in
5feet 9inches
5'-9-1/2"
5' 9-1/2"
5' 9 1/2"
6'
3/4"
3ft-6-1/4 in
"""
from pyparsing import CaselessKeyword, pyparsing_common, Optional
CK = CaselessKeyword
feet_units = CK("feet") | CK("ft") | "'"
inch_units = CK("inches") | CK("inch") | CK("in") | '"'
# pyparsing_common.number will parse an integer or real, and convert to float
integer = pyparsing_common.number
fraction = integer + '/' + integer
fraction.addParseAction(lambda t: t[0]/t[-1])
qty = fraction | (integer + Optional(fraction)).addParseAction(lambda t:sum(t))
# define whole Height feet-inches expression
HEIGHT = CK("height") | CK("ht")
inch_qty = qty("inches")
feet_qty = qty("feet")
height_parser = Optional(HEIGHT) + (inch_qty + inch_units |
feet_qty + feet_units + Optional(inch_qty + inch_units))
# use parse-time callback to convert feet-and-inches to inches
height_parser.addParseAction(lambda t: t.get("feet", 0.0)*12 + t.get("inches", 0.0))
height_parser.ignore("-")
height_parser.runTests(samples)
# how to use the parser in normal code
height_value = height_parser.parseString(samples.splitlines()[0])[0]
print(height_value, type(height_value))
Prints:
Height 5 feet 9 inch
[69.0]
5 feet 9 inch
[69.0]
5ft 9 in
[69.0]
5feet 9inches
[69.0]
5'-9-1/2"
[69.5]
5' 9-1/2"
[69.5]
5' 9 1/2"
[69.5]
6'
[72.0]
3/4"
[0.75]
3ft-6-1/4 in
[42.25]
69.0 <type 'float'>
In JavaScript, there is an operation called "computed access", done as object[key], where the object property read is determined through the result of a given expression, as an alternative to the normal . operator. Personally, I mostly use it for iteration and reading properties with hyphens and stuff, but it can also be used to get associated wanted results from an input string.
So after an entire afternoon of Googling and figuring out Python syntax, etc. I was able to write a short program to do this.
import re
import string
h = 0
r = re.compile(r'(\d+)\s*(\w+)\b')
def incr( m ):
h+=m.group(1)*({'in':1,'inches':1,'inch':1,'foot':12,'feet':12,'cm':0.3937,'centimeter':0.3937,'centimeters':0.3937}[string.lower(m.group(2))]||1) # etc. etc.
return ''
re.sub(r, incr, input)
print h
You may want to restrict the keywords usable to keep the dict from getting too big.
I tried out Stephen's code in the first comment on python 3.6 and had to tweak it to work for me:
import re
h = 0
input = '5 feet 9 inches'
r = re.compile(r'(\d)\s*(\w+)\b')
measures ={'in':1,'inches':1,'inch':1,'foot':12,'feet':12,'ft':12,'cm':0.3937,'centimeter':0.3937,'centimeters':0.3937}
def incr(m):
global h
h+=int(m.group(1))*measures[m.group(2)]
return ''
re.sub(r, incr, input)
print(h)

Categories