Find, multiply and replace numbers in strings, by line - python-3.x

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.

Related

argparse read in txt file

I am trying to read a text file. In the second step I loop through the files and then I am trying to show the results in the command line.
I have a couple of problems:
I am not sure whether I managed to read in the text file, there is no error message, but
the outcome does not come
I get an error "UnboundLocalError: local variable 'P' referenced before assignment - although
I defined the variables before the function
The function works and prints the desired value but not when running it in the command line
with argparse
The code runs as "python filename.py textfile" in the command line
Checking other threads on agrparse did not help.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('filename')
args = parser.parse_args()
A = 0 # the number of characters are 0 in the beginning
B = 0
C = 0
D = 0
with open(args.filename) as file:
def rooms():
with open("rooms.txt", "r") as in_file:
lines = in_file.readlines()
for line in lines:
if "A" in line:
W+=line.count("A") #I use the count method to count each character in a specific row
if "B" in line:
B+=line.count("B")
if "C" in line:
C+=line.count("C")
if "D" in line:
D+=line.count("D")
rooms()
# if __name__=='main__main':
print(f'total:\nA: {A} B: {B} C: {C} D: {D}')
Any help would be appreciated
There are many issues with the code if it is full code:
1)indentation : Not clear indentation in your code, so it is not executed as intended.
2)syntax: There should be at least 2 blank lines after completing your function code, so that code goes into function.
3)Separate out your function definition & function call. Create your function definition (def rooms()) outside file open.
You have some issues with you code, some of which is mentioned by KiranM's answer.
Other issues are:
You have two different sources for accepting files, argsparse and a hard coded filename.
You can accomplish want you want with a dictionary and if statement.
You read in the lines twice, with the for loop and in_file.readlines().
def room(filename::str): # or a Path object.
letters = {"A":0, "B":0, "C":0, "D":0}
with open(filename, "r") as in_file:
for line in in_file:
if line in letters:
letters[line] = letters[line] + 1
return letters
# In main:
print(room("room.txt"))

Removing a line from a file

I have a file named (data.txt):
243521,Biscuit,Flour:Cream,89.5,9,1
367534,Bread,Flour,67.3,1,2
463254,Chocolate,Cocoa butter:Sugar:Milk powder,45.6,4,0
120014,Buns,Wheat Flour,24.9,5,2
560214,Cake,Flour:Baking Powder:Cake Mix,70.5,3,1
123456,burger,bread crumbs:beef:tomato,99.9,10,0
The numbers after the last comma is sold items. I want to write a code that can delete a line just if the number after the last comma is 0. This is the code I wrote but it removes the line even if the number after the last comma is not zero :
productID=input("")
with open("data.txt","r+") as file:
lines= file.readlines()
file.seek(0)
for line in lines:
productInfo= line.split(",")
y=0
if productInfo[5]>"0":
if y==0:
print("Product cannot be removed: sold items must be 0")
y=1
elif productID not in line:
file.write(line)
file.truncate()
print("Product is removed successfully")
I regret that I do not understand what you are asking for. If you have trouble expressing a difficult question, try asking the question to a friend, and then write down what you say.
Other than the noise that y introduces for no reason, the other odd thing about this code is this comparison:
productInfo[5]>"0"
Probably that comparison does not do what you expect.
I believe you just want to know if the last token is a "0" or not. For this it is better to test for equality or inequality, instead of attempting to perform a value comparison of two strings.
String equality can be tested with ==. Check for inequality with !=.
I believe you want this:
productInfo[5] != "0"
From what I have understood, you have a file that contains comma-separated data and last value is of your interest. If that value is 0, you want to remove that line.
General idea is to read the lines in file and split the , in line and access last item. Your mistake is, as many have pointed out, you are trying to compare strings with > which is not valid in python. Following code works for me with your sample data:
#reading the lines in data as list
with open("data.txt", "r") as f:
lines = f.readlines()
new_array = []
#empty array so we can populate it with lines that don't have a 0 at the end
user_input = input("Enter a number: ") #Capturing user input
for line in lines: #iterating over all lines
line = line.split(",") #splitting , in line
if line[len(line)-1].strip() != "0" and line[0] != user_input:
#if first item and last item are not user input and 0 respectively
new_array.append(",".join(line))
elif line[len(line)-1].strip() == "0" and line[0] != user_input:
#if last item is 0 but first item is not user input
new_array.append(",".join(line))
else:
print("ignoring:", *line)
with open("data2.txt", "w") as f: #creating new data file without 0
f.writelines(new_array) #writing new array to new datafile
#data2.txt now contains only lines that have no 0 at the end

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.

python3 opening files and reading lines

Can you explain what is going on in this code? I don't seem to understand
how you can open the file and read it line by line instead of all of the sentences at the same time in a for loop. Thanks
Let's say I have these sentences in a document file:
cat:dog:mice
cat1:dog1:mice1
cat2:dog2:mice2
cat3:dog3:mice3
Here is the code:
from sys import argv
filename = input("Please enter the name of a file: ")
f = open(filename,'r')
d1ct = dict()
print("Number of times each animal visited each station:")
print("Animal Id Station 1 Station 2")
for line in f:
if '\n' == line[-1]:
line = line[:-1]
(AnimalId, Timestamp, StationId,) = line.split(':')
key = (AnimalId,StationId,)
if key not in d1ct:
d1ct[key] = 0
d1ct[key] += 1
The magic is at:
for line in f:
if '\n' == line[-1]:
line = line[:-1]
Python file objects are special in that they can be iterated over in a for loop. On each iteration, it retrieves the next line of the file. Because it includes the last character in the line, which could be a newline, it's often useful to check and remove the last character.
As Moshe wrote, open file objects can be iterated. Only, they are not of the file type in Python 3.x (as they were in Python 2.x). If the file object is opened in text mode, then the unit of iteration is one text line including the \n.
You can use line = line.rstrip() to remove the \n plus the trailing withespaces.
If you want to read the content of the file at once (into a multiline string), you can use content = f.read().
There is a minor bug in the code. The open file should always be closed. I means to use f.close() after the for loop. Or you can wrap the open to the newer with construct that will close the file for you -- I suggest to get used to the later approach.

Resources