I'm struggling to get my code to work. I've been supplied with some variables to work with: The variable P is my file path, designated as content/textfiles/empty.txt; while the variable S is my string, designated as parrot. The end goal is to find out how many times Parrot (S) appears in my text file (P). The following is the variables and information I have been supplied with, and immediately following is my crude code that is attempting to complete my task:
import sys
P= sys.argv[1]
S= sys.argv[2]
file = open(P,'r')
data = file.read()
count = 0
if S in P:
count += 1
print(count)
file.close()
The primary issue is that I am supposed to have a return of 3 for output, but my code is only counting 1 occurrence, but I have no idea why.
[Answer previously posted on question]:
file = open(P,'r')
data = file.read()
count = data.count(S)
print(count)
Related
I am currently working on a beginner problem
(https://www.reddit.com/r/beginnerprojects/comments/1i6sax/challenge_count_and_fix_green_eggs_and_ham/).
The challenge is to read through a file, replacing lower case 'i' with 'I' and writing a new corrected file.
I am at a point where the program reads the input file, replaces the relevant lower case characters, and writes a new corrected file. However, I need to also count the number of corrections.
I have looked through the .replace() documentation and I cannot see that it is possible to find out the number of replacements made. Is it possible to count corrections using the replace method?
def capitalize_i(file):
file = file.replace('i ', 'I ')
file = file.replace('-i-', '-I-')
return file
with open("green_eggs.txt", "r") as f_open:
file_1 = f_open.read()
file_2 = open("result.txt", "w")
file_2.write(capitalize_i(file_1))
You can just use the count function:
i_count = file.count('i ')
file = file.replace('i ', 'I ')
i_count += file.count('-i-')
file = file.replace('-i-', '-I-')
i_count will have the total amount of replacements made. You can also separate them by creating new variables if you want.
I want to be able to add a specific character into my file, using python code.
I have attempted using read functions, meaning lists, but those come up with an error of "TypeError: 'builtin_function_or_method"
I believe this means that python can not write a character into a specific place using the list function
Incorrect way:
file: 1)5
Code:
while true:
with open ('file','w') as f:
f.writeline[0]=+1
with open ('file','r') as f:
fc = f.read()
print (fc)
Expected output:
5,6,7,8,9,10,11,12,13,14,15....
I assumed that this line of code would increase the five until I stopped the program, but instead it sent the error code described earlier. Is there a way to write the code so that it does it as expected?
Basically, you would need to build a function to update a single character. I think this would work, but I literally wrote it in like three minutes, so take caution...
def write_at_index(filename,y_pos,x_pos,character):
"""Write a character 'character' at the given index"""
lines = 0 //begin lines outside scope of the with statement.
with open(filename,"r") as file:
lines = file.readlines()
if len(lines)<y_pos:
raise Exception('y pos out of bounds')
if len(lines[y_pos]) < x_pos
raise Exception('x_pos out of bounds')
lines[y_pos][x_pos] = character
with open(filename,"w") as file:
file.writelines(lines)
The first, your code will have an infinite loop:
while True: Do you have any check variable?
The second, I don't think this one can work for you: f.writeline[0]=+1
I'm not sure that my recommend code can help you fix your issue, but if it doesn't match your idea, please comment it.
check = True
# file = '1)5'
add_val = 5
while check:
open('file', 'w').write(add_val + ",")
add_val += 1
if add_val > 20: # condition to break the while loop
check = False
f = open('file','r').read()
print (f)
I am trying to make a simple program that takes a text file as input and then prints out a five day temperature forecast from the file. I am having trouble with getting the correct value to print from the delimited string. Any ideas where I went wrong here? My output is attached below.
print("File:")
f = input()
a = open(f, 'r')
b = a.read()
c = b.split(',')
a.close()
count = 1
for i in c:
print("Day {}: {}".format(count, c))
count = count + 1
.close() should be used on the file object.
you should use a.close() to close file.
b is a string resulting of the "read()" executed on the a object (your file)
Once you have that problem solved you can continue trying if your program is working as you expected.
Edit:
Now that you've solved that problem, there's something else I think you should look into.
On your print statement, you ouput the c array, wich comes from splitting the first line of the file, and only the first one. You're not looping through the file lines. That's why you always get the same array as output for each day.
If your goal is to print one number per day, then your code should be:
for i in c:
print("Day {}: {}".format(count, i))
count = count + 1
If your goal is to repeat this process for every line inside the file, then you should do something like:
for line in f:
#your code
So I am trying to count the number of times a certain character occurs from a score (.txt) file. The file says something like [$$$$$#$$#$$$]
Im trying to create a counter that counts the number of times $ occurs but resets every time a # happens.
This is all I have come up with so far but doesn't account for the restart.
with open ("{}".format(score), 'r') as f:
scoreLines = f.read().splitlines()
y = str(scoreLines)
$_count = int(y.count('$'))
The count is reflected in another part of the program which is outputting a wave. So every time a # occurs the wave needs to stop and start again. Any help would be appreciated!
You can simply use split
for sequence in y.split('#'):
wave_outputting_function(.., len(sequence), ...)
(assuming y contains your entire file as a string without linebreaks)
Try this using iterators:
#!/usr/bin/env python3
import sys
def handle_count(count):
print("count", count)
def main():
with open("splitter.txt", "rt") as fhandle:
for line in (d.strip() for d in fhandle):
for d in (i.count('$') for i in line.split('#')):
handle_count(d)
if __name__ == '__main__':
main()
I copied the code from a tutorial to count the number of occurrences of a word in a text file but for some reason the program miscounts by a lot (it seems to max out at 6). I have tested it using text from different files but for some reason it is not correctly counting.
This is my code:
search = input("Input your search term: ")
found = 0
with open ("search.txt", 'r') as data:
for line in data:
if search.casefold() in line.casefold():
found += 1
print(found)
Is the problem with my code?
what if you change your code to this:
search = input("Input your search term: ")
found = 0
with open ("search.txt", 'r') as data:
for line in data:
if search.casefold() in line.casefold():
found += line.casefold().count(search.casefold())
print(found)
Would this make a difference? Your code count only once if the word appears multiple times in a line.