How can I replace a line with user input? - python-3.x

I need to do this prompts in a function. Can someone please help me? I just don't understand how. I'm just a beginner.
This should be written in a function.
Prompt for two line numbers, one is the starting line of text to copy, and the second is the end line of the text to copy. Slice this part of the list, and add it to the end of the list as a single string.Check that the line numbers entered are valid. If they are invalid, ask for a line numbers again.
Prompt for a line number and then replace that line with a new one from the user. Check that the line number entered is valid. If it is invalid, ask for a line number again

Here's a skeleton to get you started. Use the input builtin function to get user input and check if they are valid in a while loop
def isValid(start, end):
# Check if your start and end numbers are value here
return start <= end
def getUserInput():
start = 0
end = -1
while True:
start = input("Enter starting line number: ")
end = input("Enter ending line number: ")
if not isValid(start, end):
print("Invalid input, try again")
else:
break
## Do what you want with the list here
return start, end

Related

Find, multiply and replace numbers in strings, by line

I'm scaling the Gcode for my CNC laser power output. The laser's "S" value maxes at 225 and the current file scale is 1000. I need to multiply only/all S values by .225, omit S values of 0, and replace in the string for each line. There are pre-designated "M", "G", "X", "Y", "Z", "F", and "S" in the Gcode for axis movement and machine functions.
Note: I can't do this manually as there's like 7.5k lines of code.
Hoping for .py with an outcome like (top 3 lines):
Old> G1Y0.1S0 New> G1Y0.1S0
Old> G1X0.1S248 New> G1X0.1S55.8
Old> G1X0.1S795.3 New> G1X0.1S178.9
Example file Code:
G1Y0.1S0
G1X0.1S248
G1X0.1S795.3
G1X0.2S909.4
G1X0.1S874
G1X0.1S374
G1X1.1S0
G1X0.1S610.2
G1X0.1S893.7
G1X0.6S909.4
G1X0.1S893.7
G1X0.1S661.4
G1X0.1S157.5
G1X0.1Y0.1S0
G1X-0.1S66.9
G1X-0.1S539.4
G1X-0.2S909.4
G1X-0.1S897.6
G1X-0.1S811
G1X-0.1S515.7
G1X-0.1S633.9
G1X-0.1S874
G1X-0.3S909.4
G1X-0.1S326.8
G1X-0.8S0
Tried this:
import os
import sys
import fileinput
print("Text to Search For:")
textToSearch = input("> ")
print("Set Max Power Output:")
valueMult = input("> ")
print("File to work:")
fileToWork = input("> ")
tempFile = open(fileToWork, 'r+')
sValue = int
for line in fileinput.input (fileToWork):
if textToSearch in line:
c = str(textToSearch,(sValue)) #This is where I'm stuck.
print("Match Found >> ", sValue)
else:
print("Match Not Found")
tempFile.write(line.replace(textToSearch, (sValue,"(sValue * (int(valueMult)/1000))")))
tempFile.close()
#input("\n\n Press Enter to Exit")
Output:
Text to Search For:
> S
Set Max Power Output:
> 225
File to work:
> test.rtf
Match Not Found
Traceback (most recent call last):
File "/Users/iamme/Desktop/ConvertGcode.py", line 25, in <module>
tempFile.write(line.replace(textToSearch, (sValue,"(sValue * (int(valueMult)/1000))")))
TypeError: replace() argument 2 must be str, not tuple
>>>
test.rtf file:
Hello World
X-095Y15S434.5
That is Solid!
Your code has a couple of issues that need to be addressed:
first, you declare the sValue variable but never assign it the value from every line in your loop,
second, said variable is an int, but should be a float or you'll lose the decimal part seen in the file,
and third, since you're not getting the corresponding values, you're not multiplying the aforementioned values by the new scale factor to then replace the old with this.
Additionally, you're opening the original file in read/write mode (r+), but I would recommend you write to a new file instead.
Now, here is your code with fixes and changes (I'm taking the liberty to write variable names in Python style):
multiplier = input("New max power output for S: ")
input_file = input("Input file: ")
output_file = input("Output file: ")
with open(input_file, 'r') as source, open(output_file, 'w') as target:
for line in source:
if 'S' in line:
line = line.removesuffix('\n')
split_line = line.split('S', -1)
new_value = float(split_line[1]) * float(multiplier)
new_line = f'{split_line[0]}S{new_value:.1f}\n'
print(f'Old> {line:25s}New> {new_line}', end='')
target.write(new_line)
else:
target.write(line)
As you can see, we open both source and target files at the same time. By using the with statement, the files are closed at the end of that block.
The code assumes the text to search will appear no more than once per line.
When a match is found, we need to remove the newline from the line (\n) so it's easy to work with the number after the S. We split the line in two parts (stored in the list split_line), and convert the second element (S's value) to a float and multiply it by the entered multiplier. Then we construct the new line with its new value, print the old and new lines, and write it to the target file. We also write the line to the target file when a match isn't found so we don't lose them.
IMPORTANT: this code also assumes no additional values appear after S{value} in the lines, as per your sample. If that is not the case, this code will fail when reaching those lines.

Trying to print the line a string appears in a text file

I am analysing an episode of Brooklyn 99 specifically trying to find the line number in a text file where Gina says Scully looks 'like an eggplant' but my code isn't working, any help would be appreciated, I am using jupyter and not getting an error message when running my code.
f = open(r'C:\Users\bubba\Downloads\B99_episode_.txt', 'r')
print(f)
# Choosing TERRY
# Initialising the value of count as -1 because it appears in the cast list
count = -1
terry_in_f = f.readlines()
for line in terry_in_f:
if 'TERRY' in line:
count = count + 1
print(count)
# Finding the line number in which Gina states 'like an eggplant'
for index, line in enumerate(f):
if line.lower() == "like an eggplant":
print(index)
break
if "like an eggplant" will always enter the block because "like an eggplant" isn't falsey. You need to check the actual line from the file is equal to the string you're looking for. So it should be if line == "like an eggplant".
Also, you want to print the line number. You can use enumerate() to give you the index of the line you're on instead of just printing the actual line itself.
for index, line in enumerate(f):
if line.lower() == "like an eggplant":
print(index)
break
Lastly, instead of doing a hard comparison of if line == "like an eggplant":, it may be better to do if "like an eggplant" in line:. This will return true if the string "like an eggplant" is in the script line, even if there is some surrounding noise. For example, if the script says "Gina: like an eggplant", having a direct comparison would return false. Checking if the string is inside the line would return True. It gives you more flexibility.

Find items in a text file that is a incantinated string of capitalized words that begin with a certain capital letter in python

I am trying to pull a string of input names that get saved to a text file. I need to pull them by capital letter which is input. I.E. the saved text file contains names DanielDanClark, and I need to pull the names that begin with D. I am stuck at this part
for i in range(num):
print("Name",i+1," >> Enter the name:")
n=input("")
names+=n
file=open("names.txt","w")
file.write(names)
lookUp=input("Did you want to look up any names?(Y/N)")
x= ord(lookUp)
if x == 110 or x == 78:
quit()
else:
letter=input("Enter the first letter of the names you want to look up in uppercase:")
file=open("names.txt","r")
fileNames=[]
file.list()
for letter in file:
fileNames.index(letter)
fileNames.close()
I know that the last 4 lines are probably way wrong. It is what I tried in my last failed attempt
Lets break down your code block by block
num = 5
names = ""
for i in range(num)
print("Name",i+1," >> Enter the name:")
n=input("")
names+=n
I took the liberty of giving num a value of 5, and names a value of "", just so the code will run. This block has no problems. And will create a string called names with all the input taken. You might consider putting a delimiter in, which makes it more easier to read back your data. A suggestion would be to use \n which is a line break, so when you get to writing the file, you actually have one name on each line, example:
num = 5
names = ""
for i in range(num)
print("Name",i+1," >> Enter the name:")
n = input()
names += n + "\n"
Now you are going to write the file:
file=open("names.txt","w")
file.write(names)
In this block you forget to close the file, and a better way is to fully specify the pathname of the file, example:
file = open(r"c:\somedir\somesubdir\names.txt","w")
file.write(names)
file.close()
or even better using with:
with open(r"c:\somedir\somesubdir\names.txt","w") as openfile:
openfile.write(names)
The following block you are asking if the user want to lookup a name, and then exit:
lookUp=input("Did you want to look up any names?(Y/N)")
x= ord(lookUp)
if x == 110 or x == 78:
quit()
First thing is that you are using quit() which should not be used in production code, see answers here you really should use sys.exit() which means you need to import the sys module. You then proceed to get the numeric value of the answer being either N or n and you check this in a if statement. You do not have to do ord() you can use a string comparisson directly in your if statement. Example:
lookup = input("Did you want to look up any names?(Y/N)")
if lookup.lower() == "n":
sys.exit()
Then you proceed to lookup the requested data, in the else: block of previous if statement:
else:
letter=input("Enter the first letter of the names you want to look up in uppercase:")
file=open("names.txt","r")
fileNames=[]
file.list()
for letter in file:
fileNames.index(letter)
fileNames.close()
This is not really working properly either, so this is where the delimiter \n is coming in handy. When a text file is opened, you can use a for line in file block to enumerate through the file line by line, and with \n delimiter added in your first block, each line is a name. You also go wrong in the for letter in file block, it does not do what you think it should be doing. It actually returns each letter in the file, regardless of whay you type in the input earlier. Here is a working example:
letter = input("Enter the first letter of the names you want to look up in uppercase:")
result = []
with open(r"c:\somedir\somesubdir\names.txt", "r") as openfile:
for line in openfile: ## loop thru the file line by line
line = line.strip('\n') ## get rid of the delimiter
if line[0].lower() == letter.lower(): ## compare the first (zero) character of the line
result.append(line) ## append to result
print(result) ## do something with the result
Putting it all together:
import sys
num = 5
names = ""
for i in range(num)
print("Name",i+1," >> Enter the name:")
n = input("")
names += n + "\n"
with open(r"c:\somedir\somesubdir\names.txt","w") as openfile:
openfile.write(names)
lookup = input("Did you want to look up any names?(Y/N)")
if lookup.lower() == "n":
sys.exit()
letter = input("Enter the first letter of the names you want to look up in uppercase:")
result = []
with open(r"c:\somedir\somesubdir\names.txt", "r") as openfile:
for line in openfile:
line = line.strip('\n')
if line[0].lower() == letter.lower():
result.append(line)
print(result)
One caveat I like to point out, when you create the file, you open the file in w mode, which will create a new file every time, therefore overwriting the a previous file. If you like to append to a file, you need to open it in a mode, which will append to an existing file, or create a new file when the file does not exist.

running a while loop in python and functions not defined

Hi I have this code below and I want the while loop to keep on getting an input from the user whenever the user enters an empty value or doesn't input any value, the program should keep on prompting the user to enter at least a single character, but the code seems to run even though I don't enter any value, thus an empty string the code still executes the (function) in the code, and also I get error "Function not defined"
word = ""
while True:
if word != "":
def str_analysis(string):
if string.isdigit():
if int(string) > 99:
print (string,"Is a big number")
else:
print(string,"Small number")
elif string.isalpha():
print(string,"Is all alphabetical characters")
else:
print(string,"is multiple character types")
word = input ("Enter a word or integer:")
break
str_analysis(word)
I don't know what you expect to happen. word is equal to "" so the if block won't run, so the function won't get defined. Next, we ask the user for input and after that break the loop. Then you try and call a function that was never defined.
What you wanna do is put a break at the end of the function and get rid of the existing one.

Only read first line of a text file

I have a text file named "paintingJobs". The data looks like this:
E5341,21/09/2015,C102,440,E,0
E5342,21/09/2015,C103,290,A,290
E5343,21/09/2015,C104,730,N,0
E5344,22/09/2015,C105,180,A,180
I have written a program that only finds the first entry but cannot find any data beyond the first line (I think it is to do with Python including /n in front of the username) The program looks like this.
def ASearch():
print("Option A: Search for an estimate")
print("Please enter the estimate number: ")
estimateNumber = str(input())
file = open("paintingJobs.txt", "r")
paintJobs = file.readlines()
file.close()
length = len(paintJobs)
paintData = []
for line in paintJobs:
estNumber, estDate, CustID, FinalTotal, Status, AmountPaid = line.split(",")
if estimateNumber == estNumber:
print("Estimate number: ", estNumber)
print("Customer ID: ", CustID)
options()#this is a function in a for a different part of the program that works fine
else:
print("You have entered an incorrect estimate number; please try again")
ASearch()
How do I get the program to read (and return the values of) the second entry in the list E.G. E5342 (any help would be appreciated greatly)

Resources