I'm new to python and I'm trying a new problem but couldn't get the solution. I've a text file called replace.txt with the contents like this:
81, 40.001, 49.9996, 49.9958
82, 41.1034, 54.5636, 49.9958
83, 44.2582, 58.1856, 49.9959
84, 48.7511, 59.9199, 49.9957
85, 53.4674, 59.3776, 49.9958
86, 57.4443, 56.6743, 49.9959
87, 59.7, 52.4234, 49.9958
Now I have one more file called actual data and it has a huge amount of data like the one above now I want to replace the above lines in actualdata.txt by matching the first number like search for '81' in actualdata.txt and replace it with line having '81' in replace.txt
here the actualdata.txt looks like this:
--------lines above--------
81, 40.0 , 50.0 , 50.0
82, 41.102548189607, 54.564575695695, 50.0
83, 44.257790830341, 58.187003960661, 50.0
84, 48.751279796738, 59.921728571875, 50.0
85, 53.468166336575, 59.379329520912, 50.0
86, 57.445611860313, 56.675542227082, 50.0
87, 59.701750075154, 52.424055585018, 50.0
88, 59.725876387298, 47.674633684987, 50.0
89, 57.511209176153, 43.398353484768, 50.0
90, 53.558991157616, 40.654756186166, 50.0
91, 48.853051436724, 40.06599229952 , 50.0
92, 44.335578609695, 41.75898487363 , 50.0
93, 41.139049269956, 45.364964707822, 50.0
94, 4.9858306110506, 4.9976785333108, 50.0
95, 9.9716298556132, 4.9995886389273, 50.0
96, 4.9712790759448, 9.9984071508336, 50.0
97, 9.9421696473295, 10.002460334272, 50.0
98, 14.957223264745, 5.0022762348283, 50.0
99, 4.9568005100444, 15.000751982196, 50.0
------lines below----------
How can I do this please help me I 'm trying to use fileinput and replace but I'm not getting the output.
this is the sample code which I'm still improvising (this is working fyn for one line):
oldline=' 82, 41.102548189607, 54.564575695695, 50.0'
newline=' 81, 40.001, 49.9996, 49.9958'
for line in fileinput.input(inpfile, inplace = 1):
print line.replace(oldline,newline),
this is the code I wrote finally :
replacefile= open('temp.txt','r')
for line1 in replacefile:
newline = line1.rstrip()
rl=newline
rl=rl.split()
search =rl[0]
with open(inpfile) as input:
intable = False
for line in input:
fill=[]
if line.strip() == "*NODE":
intable = True
if line.strip() == "---------------------------------------------------------------":
intable = False
if intable:
templine=(line.rstrip())
tl=line.rstrip()
tl= tl.split()
if tl[0] == search:
oldline=templine
for line2 in fileinput.input(inpfile, inplace = 1):
line2.replace(oldline,newline)
But I couldn't get the output the contents of the actualdata.txt are getting deletd, help me with this
output I wanted is to change the actualdata.txt like this:
-------lines above------
81, 40.001, 49.9996, 49.9958
82, 41.1034, 54.5636, 49.9958
83, 44.2582, 58.1856, 49.9959
84, 48.7511, 59.9199, 49.9957
85, 53.468166336575, 59.379329520912, 50.0
86, 57.445611860313, 56.675542227082, 50.0
87, 59.701750075154, 52.424055585018, 50.0
88, 59.725876387298, 47.674633684987, 50.0
89, 57.511209176153, 43.398353484768, 50.0
90, 53.558991157616, 40.654756186166, 50.0
-------lines below------
Use fileinput module to replace lines inplace:
import fileinput
def get_next_line(fptr):
x = fptr.readline()
if(x != ''):
return x.strip(), x.strip().split()[0].strip()
else:
return '',''
f = open("replace.txt", "r")
f_line, f_line_no = get_next_line(f)
for line in fileinput.input("actualdata.txt", inplace=True):
if(line.strip().split()[0].strip() == f_line_no): #if line number matches
print(f_line) # write newline
f_line, f_line_no = get_next_line(f) # Get next newline
else: # Otherwise
print(line.strip()) # write original one
By the way I am using python3. Make appropriate changes if you are using python2
Is replace.txt is also big? If not, you can load that first into memory, build a dictionary and use it to replace lines in actualdata.txt
Here's what I am doing:
First open replace.txt and build a dictionary. Since you are replacing the lines by the first value of the line, we make that as dictionary key. And the whose value will be line you want to replace. Like:
replacement_data = {
'81': '81, 40.001, 49.9996, 49.9958',
'82': 82, 41.1034, 54.5636, 49.9958,
...
...
}
Next we start reading the actualdata.txt file, line by line. So, we have to find if the first number of this line whether to be replaced or not. So, we will first split it by ,, get the first character and see if it is present in replacement_data dictionary. If it is present, we will replace it and if not, we will simply ignore.
line = "83, 44.257790830341, 58.187003960661, 50.0"
first_char = line.split(',')[0].strip() #first char is 83
# lets check whether to replace it or not
if first_char in replacement_data.keys():
# if key exists, we have to replace
line = replacement_data[first_char]
print line # so that it writes to file
Putting all pieces together:
import fileinput
import sys
inpfile = 'actualdata.txt'
replacement_file = 'replace.txt'
replacement_data = {}
with open(replacement_file) as f:
for line in f:
key = line.split(',')[0].strip()
replacement_data[key] = line
for line in fileinput.input(inpfile, inplace = 1):
first_char = line.split(',')[0].strip()
try:
int(first_char)
line = replacement_data[first_char]
print line,
except (ValueError, KeyError):
print line,
continue
It generates the original file to:
--------lines above--------
81, 40.001, 49.9996, 49.9958
82, 41.1034, 54.5636, 49.9958
...
...
86, 57.4443, 56.6743, 49.9959
87, 59.7, 52.4234, 49.9958 88, 59.725876387298, 47.674633684987, 50.0
89, 57.511209176153, 43.398353484768, 50.0
...
99, 4.9568005100444, 15.000751982196, 50.0
------lines below----------
Related
I wrote functions to call and replace tuples from a dictionary. The functions all work independently. When I run them individually the tuple values return integers as planned. When run in sequence or nested with other functions, the tuples return NoneType error. When I run type on my called tuple it returns integer. I'm confused and wanted to solve this issue before I convert to a class structure to tidy up.
My current workflow is: takes in an integer determined from previous code (volume)> conditionally chooses a divisor> rounds down the value> matches the value in a dictionary> returns the value from the dictionary> new tuple created> tuple in dictionary is replaced
TypeError Traceback (most recent call last)
<ipython-input-23-1f1ae48bdda3> in <module>
----> 1 asp_master(275,dict_tuberack1,vol_tuberack1,tuberack1,'A1')
2 height_a1= get_height(dict_tuberack1,tuberack1,'A1')
3 asp_a(275,height_a1,tuberack1['A1'])
4 disp_master(275,dict_tuberack1,vol_tuberack1,tuberack1,'A2')
5 height_a2= get_height(dict_tuberack1,tuberack1,'A2')
<ipython-input-10-ba8bc2194a15> in asp_master(volume, dict_vol, dict_labware, labware, well)
1 def asp_master(volume,dict_vol,dict_labware,labware,well):
----> 2 if low_vol_check(volume,dict_labware,labware,well)==True:
3 new_vol=volume_sub(volume,dict_labware,labware,well)
4 tup_update_sub(new_vol,dict_vol,dict_labware,labware,well)
5 print(dict_labware[labware[well]])
<ipython-input-16-a23165d51020> in low_vol_check(volume, dict_labware, labware, well)
10
11 def low_vol_check(volume,dict_labware,labware,well):
---> 12 x=get_volume(dict_labware,labware,well)
13 y=volume
14 if x-y < 0:
<ipython-input-16-a23165d51020> in get_volume(dict_labware, labware, well)
1 def get_volume(dict_labware,labware,well):
2 tup = dict_labware.get(labware[well])
----> 3 (tup_v,tup_h)=tup
4 volume=tup_v
5 return tup_v
TypeError: cannot unpack non-iterable NoneType object
Robot Code:
from opentrons import protocol_api
from opentrons.simulate import get_protocol_api
from math import floor,ceil
from datetime import datetime
import opentrons
protocol = get_protocol_api('2.8')
tuberack1 = protocol.load_labware('opentrons_15_tuberack_nest_15ml_conical','2', 'tuberack1')
tuberack2 = protocol.load_labware('opentrons_24_tuberack_nest_1.5ml_snapcap','3','tuberack2')
tiprack= protocol.load_labware('opentrons_96_tiprack_300ul','4')
p300 = protocol.load_instrument('p300_single', 'left', tip_racks=[tiprack])
p300.home
Code:
dict_tuberack1={tuberack1['A1']:(14000,104), tuberack1['A2']:(14000,104), tuberack1['A3']:(14000,104),}
vol_tuberack1= {14000: 104, 13500: 101, 13000: 98, 12500: 94,
12000: 91, 11500: 88, 11000: 85, 10500: 81,
10000: 78, 9500: 75, 9000: 72, 8500: 68,
8000: 65, 7500: 62, 7000: 59, 6500: 55,
6000: 52, 5500: 49,}
def get_volume(dict_labware,labware,well):
tup = dict_labware.get(labware[well])
(tup_v,tup_h)=tup
volume=tup_v
return tup_v
def low_vol_check(volume,dict_labware,labware,well):
x=get_volume(dict_labware,labware,well)
y=volume
if x-y < 0:
return False
else:
return True
def tup_update_sub(volume,dict_vol,dict_labware,labware,well):
tup = dict_labware.get(labware[well])
adj_list=list(tup)
adj_list[0]=volume
divisor=1
if volume >=1000:
divisor=1000
vol_even=round_down(volume, divisor)
elif 100 <= volume <1000: #this was the issue and was fixed.
divisor=100
vol_even=round_down(volume,divisor)
else:
divisor=10
vol_even=round_down(volume,divisor)
new_height=dict_vol.get(vol_even)
adj_list[1]=new_height
new_tup=tuple(adj_list)
dict_labware[labware[well]] = new_tup
def asp_master(volume,dict_vol,dict_labware,labware,well):
if low_vol_check(volume,dict_labware,labware,well)==True:
new_vol=volume_sub(volume,dict_labware,labware,well)
tup_update_sub(new_vol,dict_vol,dict_labware,labware,well)
print(dict_labware[labware[well]])
else:
print('Cannot aspirate')
#robot commands below
def asp_a (volume,height,source):
p300.pick_up_tip()
p300.aspirate(volume, source.bottom(z=height))
def disp_a (volume,height,destination):
p300.dispense(volume,destination.bottom(z=height+8))
p300.blowout(height+8)
#code that generated error message below
asp_master(275,dict_tuberack1,vol_tuberack1,tuberack1,'A1')
height_a1= get_height(dict_tuberack1,tuberack1,'A1')
asp_a(275,height_a1,tuberack1['A1'])
I have a task for my college (I am beginner), which asks you to validate a password using ASCII characters. I tried using simple code and it worked, however it kept skipping my ASCII part.
Requirement list:
1.4 Call function to get a valid password OUT: password
1.4.1 Loop until password is valid
1.4.2 Ask the user to enter a password
1.4.3 Check that the first character is a capital letter (ASCII values 65 to 90)
1.4.4 Check that the last character is #, $ or % (ASCII values 35 to 37) 1.4.5 Return a valid password
U = [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]
upCase = ''.join(chr(i) for i in U)
print(upCase) #Ensure it is working
def passVal(userPass):
SpecialSym = ["#", "$", "%"]
val = True
#Common way to validate password VVV
if len(userPass) < 8:
print("Length of password should be at least 8")
val = False
if not any(char.isdigit() for char in userPass):
print("Password should have at least one numeral")
val = False
#I Tried same with ASCII (and other methods too) but it seemed to be skipping this part VVV
if not any(upCase for char in userPass):
print("Password should have at least one uppercase letter")
val = False
if not any(char.islower() for char in userPass):
print("Password should have at least one lowercase letter")
val = False
if not any(char in SpecialSym for char in userPass):
print("Password should have at least on fo the symbols $%#")
val = False
if val:
return val
def password():
if (passVal(userPass)):
print("Password is valid")
else:
print("Invalid Password !!")
userPass = input("Pass: ")
password()
From Python 3.7 you can use str.isascii()...
>>> word = 'asciiString'
>>> word.isascii()
True
Otherwise you could use:
>>> all([ord(c) < 128 for c in word])
True
Since all ASCII characters have an ordinal (ord) value less than 128 (0 -> 127): https://en.wikipedia.org/wiki/ASCII
So your logic will either be (3.7+):
if word.isascii():
# string is ascii
...
Or:
if all([ord(c) < 128 for c in word]):
# string is ascii
else:
# string contains at least one non-ascii character
This is my first ever computer science course so forgive me if this answer is really obvious. I wrote the below code and it worked just fine. I just needed to add an else statement to account for an invalid name input.
Here is is before:
mynames = ['Naomi', 'James', 'Amos', 'Alex', 'Bobbie', 'Josephus', 'Fred', 'Camina', 'Julie', 'Prax', 'Christien', 'Anderson', 'Havelock', 'Ashford', 'Bull', 'Anna', 'Arjun', 'Souther', 'Carissa', 'Samara']
myscores = [89, 98, 76, 76, 84, 93, 82, 64, 63, 75, 76, 86, 96, 75, 86, 100, 99, 87, 84, 94]
name = input("Please enter a name:")
#search through mynames to find the name
while name!='q':
for x in range(20):
if mynames[x] == name:
print(mynames[x], "scored", myscores[x])
name = input("Please enter a name:")
And here it is after:
mynames = ['Naomi', 'James', 'Amos', 'Alex', 'Bobbie', 'Josephus', 'Fred', 'Camina', 'Julie', 'Prax', 'Christien', 'Anderson', 'Havelock', 'Ashford', 'Bull', 'Anna', 'Arjun', 'Souther', 'Carissa', 'Samara']
myscores = [89, 98, 76, 76, 84, 93, 82, 64, 63, 75, 76, 86, 96, 75, 86, 100, 99, 87, 84, 94]
name = input("Please enter a name:")
#search through mynames to find the name
while name!='q':
for x in range(20):
if mynames[x] == name:
print(mynames[x], "scored", myscores[x])
else:
print("That name is not in this class.")
name = input("Please enter a name:")
name = input("Please enter a name:")
It just keeps printing "That name is not in this class." no matter what I type in. SOS
The if statement is evaluated each time through the loop, so you need to keep track of whether the name has been found, and then only print at the end.
For example:
while name!='q':
found = False
for x in range(20):
if mynames[x] == name:
print(mynames[x], "scored", myscores[x])
found = True
break
if not found:
print("That name is not in this class.")
name = input("Please enter a name:")
I think you will really benefit here from using a dictionary. See the following example.
mynames = ['Naomi', 'James', 'Amos', 'Alex', 'Bobbie', 'Josephus', 'Fred', 'Camina', 'Julie', 'Prax', 'Christien', 'Anderson', 'Havelock', 'Ashford', 'Bull', 'Anna', 'Arjun', 'Souther', 'Carissa', 'Samara']
myscores = [89, 98, 76, 76, 84, 93, 82, 64, 63, 75, 76, 86, 96, 75, 86, 100, 99, 87, 84, 94]
name_score_map = dict(zip(mynames, myscores))
name = input("Please enter a name:")
#search through mynames to find the name
while name!='q':
if name in name_score_map:
print(name, "scored", name_score_map[name])
else:
print("That name is not in this class.")
name = input("Please enter a name:")
In the first line, we construct a dictionary that maps the name of a student to the score they got. This takes away the need to iterate through the mynames list to see if a name is in it and then using the corresponding index to grab the score. This, in effect, removes the issue you were facing with print("That name is not in this class.") executing for every iteration in which mynames[x] != name.
We can then check if the name has a score by seeing if the name is in name_score_map. This reduces the time complexity of the search from O(n) to O(1). We can then grab score simply by using the name as a key to the name_score_map dictionary.
I am trying to decode a Huffman encoded string, with the following script:
def decode(input_string, lookup_table):
codes = lookup_table.keys()
result = bytearray()
i = 0
while len(input_string[i:]) != 0:
for code in codes:
if input_string[i:].startswith(code):
result.append(lookup_table[code])
i += len(code)
break
return ''.join((chr(x) for x in result))
lookup_table = {'10': 108, '00': 111, '0111': 114, '010': 119, '0110': 72, '1111': 33, '1110': 32, '1100': 100, '1101': 101}
input_string = '0110110110100011100100001111011001111'
print decode(input_string, lookup_table)
This script gives as output:
'Hello world!'
The script works for this small string, but decoding an encoded version of Hamlet takes 110 seconds. Is there a more efficient and faster way to do this?
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 5 years ago.
While writing a project for fun, I came across an unfamiliar issue with If and Elif statements. For some reason when the user inputs a dog "type", python ignores the if statements and continues on using the rest of the statement. The program was written in Python 3.6. I have no clue as to why the if and elif statements aren't working properly. Is there a formatting/syntax issue that I am not aware of? Thanks in advance!
def small():
small_list = [0, 15, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80]
small_input = input("How old is your dog?")
print(small_input)
small_age = int(small_input)
small_set2 = small_list[small_age]
print("Your dog's age is: " + str(small_set2))
def medium():
medium_list = [0, 15, 24, 28, 32, 36, 42, 47, 51, 56, 60, 65, 69, 74, 78, 83, 87]
medium_input = input("How old is your dog?")
print(medium_input)
medium_age = int(medium_input)
medium_set2 = medium_list[medium_age]
medium_set2 = str(medium_set2)
print("Your dog's age is: " + str(medium_set2))
def large():
large_input = input("How old is your dog?")
print(large_input)
large_set = [0, 15, 24, 28, 32, 36, 45, 50, 55, 61, 66, 72, 77, 82, 88, 93, 120]
large_age = int(large_input)
large_set2 = large_set[large_age]
large_set2 = str(large_set2)
print("Your dog's age is: " + str(large_set2))
def dog():
dog1 = input('What size dog do you have?')
print(dog1)
if dog1 == 'Small' or 'small':
print("Okay, you have a small dog.")
small()
elif dog1 == 'Medium' or 'medium':
print("Okay, you have a medium dog.")
medium()
elif dog1 == 'Large' or 'large':
print("Okay, you have a large dog.")
large()
else:
print("Sorry, I did not understand that.")
dog()
dog()
if dog1 == 'Small' or 'small':
This statement parses as:
if (dog1 == 'Small') or ('small'):
Because non-empty strings are always truthy, this is equivalent to:
if (dog1 == 'Small') or True:
So the condition is always met.
You probably want this instead:
if dog1 in ('Small', 'small'):
Or even better (ignore all the capitalisation issues):
if dog1.lower() == 'small':