Trying to print the line a string appears in a text file - python-3.x

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.

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.

Problem with reading text then put the text to the list and sort them in the proper way

Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.
This is the question my problem is I cannot write a proper code and gathering true data, always my code gives me 4 different lists for each raw!
** This is my code**
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line=line.rstrip()
line =line.split()
if line in last:
print(true)
else:
lst.append(line)
print(lst)
*** the text is here, please copy and paste in text editor***
But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
You are not checking the presence of individual words in the list, but rather the presence of the entire list of words in that line.
With some modifications, you can achieve what you are trying to do this way:
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line = line.rstrip()
words = line.split()
for word in words:
if word not in lst:
lst.append(word)
print(lst)
However, a few things I would like to point out looking at your code:
Why are you using rstrip() instead of strip()?
It is better to use list = [] as opposed to your lst = list(). It is shorter, faster, more Pythonic and avoids the use of this confusing lst variable.
You should want to remove punctuation marks attached to words, eg: ,.: which do not get removed by split()
If you want a loop body to not do anything, use pass. Why are you printing true? Also, in Python, it's True and not true.

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

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.

string.find() aways evaluate to true

I have a small script that reads a file. After reading a line i'm trying to figure out that the particular line have a especific text in it. For so i do like this
for line in file:
line = line.lower()
if line.find('my string'):
print ('found my string in the file')
reading the file that line.find aways evaluate to true. When i do like
for line in file:
line = line.lower()
if 'one big line'.find('my string'):
print ('found my string in the file')
It evaluate to false, as it suppose to do. As i'm realy new to python programming just for what i've shown i just cant think of what i might look for...
find returns a number that's the position of the occurring string inside the search string. If it does not find it, it return -1. And every number that's not 0 in python evaluates to True. That's why your code always evaluates to True.
You need something like:
if 'one big line'.find('my string') >= 0:
print ('found my string in the file')
Or, better:
idx = 'one big line'.find('my string')
if idx >= 0:
print ("found 'my string' in position %d" % (idx))
It's better idiomatic python to write this as:
for line in file:
line = line.lower()
if 'my string' in line:
print ('found my string in the file')
rather than using .find() if you don't care about the position within the string.

Resources