python 3.4 Counting occurrences in a .txt file - python-3.x

I am writing a "simple" little program for a class i am taking. this is supposed ask me for what team to search for and then return the number of times it appears on the list in a .txt file. it requests input like it should and seems to run great! its been running for an hour now :) i am getting no errors at all it seems to be stuck in a loop.
thank you all in advance for your help!
here is my code
count = 0
def main():
# open file
teams = open('WorldSeriesWinners.txt', 'r')
# get input
who = input('Enter team name: ')
#begin search
lst = teams.readline()
while lst != '':
if who in lst:
count += 1
teams.close()
print(count)
main()

You don't need to go through the file counting lines manually. You can just use .read():
count = lst.count(who)
The other problem is that you're calling teams.close() and print(count) outside of the function.
That means they'll try to execute before you call main, and you're trying to close 'teams' which hasn't been opened or defined yet, so your code doesn't know what to do. The same is with printing count - count hasn't been defined outside of the function, which hasn't been called.
If you want to use them outside the function, at the end of the function you need to return count
Also, in your loop, you're executing the statement count += 1 which means count = count + 1, but you haven't told it what count is the first time it runs, so it doesn't know what it should add to one. Fix this by defining count = 0 before the loop inside the function.
And the reason you have an infinite loop is because your condition will never be satisfied. Your code should never take an hour to execute, like, pretty much never. Don't just leave it running for an hour.
Here's some alternative code. Make sure you understand the problems though.
def main():
file = open('WorldSeriesWinners.txt', 'r').read()
team = input("Enter team name: ")
count = file.count(team)
print(count)
main()
You can literally put this entire program into one line:
print(open('WorldSeriesWinners.txt', 'r').read().count(input("Enter team name: ")))

According to the docs :https://docs.python.org/3/library/io.html#io.IOBase.readline, readline returns single line, so in your program you have infinite loop with first line of the file
while lst != ''
You can try something like
for line in teams:
if who in line:
count += 1

If you don't mind lowercase or uppercase, you can use this modified version of #charles-clayton response!
print(open('WorldSeriesWinners.txt', 'r').read().lower().count(input("Enter team name: ").lower()))

Related

Word "None" on line below input [duplicate]

This question already has answers here:
Why does my input always display none in python? [closed]
(2 answers)
Closed 23 days ago.
I wrote a simple program to track household items and output to a text file, with a while loop to have it keep running till "exit" is entered. I get the word "None" on the line below the input line when I haven't written it to do so. Here is my code.
HouseHoldItems = open('C:\\_PythonClass\\Assignment03\\HouseHoldItemsAndValue.txt', mode='a')
Items = ''
Value = ''
# while loop to keep program running until user enters "Exit"
while(True):
# Items is the primary variable, determines if user is entering new household item or wants to end the program
Items = input(print("Enter an Item (Or type 'Exit' to quit) : "))
# If statement to determine if user wants to end program
if(Items.lower() == "exit"):
break
# Else statement to write household items to the file, followed by value of items
else:
HouseHoldItems.write(Items + ', ')
Value = input(print("Enter an estimated Value: "))
HouseHoldItems.write(Value + '\n')
HouseHoldItems.close()
Here is a snip of the way the code looks as I input data items. (https://i.stack.imgur.com/CHOWk.png)
Is it part of the while(true) piece that is making it do this? Thanks for the help in advance.
You do not need to use the print function when using the input function.
Use:
Items = input("Enter an Item (Or type 'Exit' to quit) : ")
and:
Value = input("Enter an estimated Value: ")
While we're at it, in test conditions for while and if statements while your code works as is, it is not considered 'pythonic'. The pythonic way is to not use parentheses. ie
While True:
and:
if Items.lower() == "exit":

not getting return value through function or method in python

in this program i am iterating the function and adding the result into the file it works fine, no issue whatsoever but when i am trying to take the value from the return of last call, it just return nothing even though the variable is not empty.because the else part only runs for a single time.
#this is an ipynb file so spacing means they are getting executed from different blocks
def intersection(pre,i=0,point=0,count=0,result=dt):
index=-1
prefer=[]
# print(i)
if(0<i):
url = "../data/result.csv"
result= pd.read_csv(url,names=["a","b","c","d","e"])
if(i<len(pre)):
for j in result[pre[i]]:
index=index+1
if(demand[pre[i]][1] >= j):
prefer.append(result.iloc[index,:])
i=i+1
file = open('../data/result.csv', 'w+', newline ='')
header = ["a","b","c","d","e"]
writer = csv.DictWriter(file, fieldnames = header)
# writing data row-wise into the csv file
writer.writeheader()
# writing the data into the file
with file:
write = csv.writer(file)
write.writerows(prefer)
count=count+1
# print(prefer,count) print the outputs step by step
intersection(pre,i,point,count,result)
else:
print("Else Part",type(result))
print(result)
return result
#
pre=["a","b","c"]
rec=intersection(pre)
print(rec)
Output
it prints all the value of result from else part i have excluded it in snapshot because it was too vast and i have few fields here but it wil not effect, for the problem which i am getting... please answer if you know how can i take the value of result into rec.
OK. The code is a bit more complex than I thought. I was trying to work through it just now, and I hit some bugs. Maybe you can clear them up for me.
In the function call, def intersection(pre,i=0,point=0,count=0,result=dt):, dt isn't defined. What should it be?
On the fourth line, i<0 - the default value of i is zero so, unless i is given a value on calling the function, this piece of code will never run.
I notice that the file being read and the file being written are the same: ../data/result.csv - is this correct?
There's another undefined variable, demand, on line 14. Can you fill that in?
Let's see where we are after that.

Updating values in an external file only works if I restart the shell window

Hi there and thank you in advance for your response! I'm very new to python so please keep that in mind as you read through this, thanks!
So I've been working on some code for a very basic game using python (just for practice) I've written out a function that opens another file, selects a variable from it and adjusts that variable by an amount or if it's a string changes it into another string, the funtion looks like this.
def ovr(file, target, change):
with open(file, "r+") as open_file:
opened = open_file.readlines()
open_file.close()
with open(file, "w+") as open_file:
position = []
for appended_list, element in enumerate(opened):
if target in element:
position.append(appended_list)
if type(change) == int:
opened[position[0]] = (str(target)) + (" = ") + (str(change)) + (str("\n"))
open_file.writelines(opened)
open_file.close()
else:
opened[position[0]] = (str(target)) + (" = ") + ("'") + (str(change)) + ("'") + (str("\n"))
open_file.writelines(opened)
open_file.close()
for loop in range(5):
ovr(file = "test.py", target = "gold", change = gold + 1)
At the end I have basic loop that should re-write my file 5 times, each time increasing the amount of gold by 1. If I write this ovr() funtion outside of the loop and just run the program over and over it works just fine increasing the number in the external file by 1 each time.
Edit: I should mention that as it stands if I run this loop the value of gold increases by 1. if I close the shell and rerun the loop it increases by 1 again becoming 2. If I change the loop to happen any number of times it only ever increases the value of gold by 1.
Edit 2: I found a truly horrific way of fixing this isssue, if anyone has a better way for the love of god please let me know, code below.
for loop in range(3):
ovr(file = "test.py", target = "gold", change = test.gold + 1)
reload(test)
sleep(1)
print(test.gold)
The sleep part is because it takes longer to rewrite the file then it does to run the full loop.
you can go for a workaround and write your new inforamtion into a file called: file1
So you can use ur working loop outside of the write file. Anfter using your Loop you can just change the content of your file by the following steps.
This is how you dont need to rewrite your loop and still can change your file content.
first step:
with open('file.text', 'r') as input_file, open('file1.txt', 'w') as output_file:
for line in input_file:
output_file.write(line)
second step:
with open('file1.tex', 'r') as input_file, open('file.tex', 'w') as output_file:
for line in input_file:
if line.strip() == '(text'+(string of old value of variable)+'text)':
output_file.write('text'+(string of new value of variable)+' ')
else:
output_file.write(line)
then you have updated your text file.

Why is my program refrenceing the readline command multiple times and how do I stop it

Okay. So I am trying to make a code which is basically a guess the word game. since it is for a school assignment there are certain required parts such as the used of 4 functions and those functions doing certain things. the program need to pull information off of an words sheet which is stored on an external .txt file. When I try to use a line from said using the readline command it will move to the next line every time I reference the function which leaves me in a pickle.
Here is the code
import random
#Variables
file = open('words.txt','r')
Number_of_lines = 0
Correct = 'Place holder'
Score = 0
#Retrieve the next word through readline command
def get_a_Word():
Basic_Word = file.readline()
Word = Basic_Word
Word = Word
return Word
#Turn the word into a guess word
def guess_Word():
Word = get_a_Word()
Edited_Word = '*' + Word[1:]
return Edited_Word
def check_Word(Word):
if Word == get_a_Word():
return True
else:
return False
#Put that shit together
def Main():
Line = 0
while Line < 10:
Edited_Word = guess_Word()
Score = 0
Line = Line + 1
Word = input('Given {} What is the word? '.format(Edited_Word))
Word = Word.upper()
if check_Word(Word) == True:
print('That is correct!')
Score = Score + 10
elif check_Word(Word) == False:
print('That is incorrect. the word was {}.'.format(get_a_Word()))
else:
print('you broke it')
Correct = Score/10
print('You have successfully guessed {} out of 10 words. Your final score is {}.' .format(Correct, Score))
Main()
file.close()
The .txt File contains these word in this order
Store
Apple
Bicycle
Water
Mercedes
Classroom
Architect
Elevator
Measurement
Godzilla
Any help would be appreciated!
I don't know exactly how the functions you're supposed to have are specified, but the obvious solution to not getting multiple different words is simply not to call get_a_Word more than once per cycle of the main loop. Some of the other functions may need to be changed to take the previously fetched word as an argument.
The loop would look something like this (pseudocode, I may be skipping some things):
while line < 10:
word = get_a_Word()
edited_word = guess_Word(word)
guess = input('Given {} What is the word? '.format(edited_word))
if check_Word(word, guess):
print('That is correct!')
score += 10
else:
print('That is incorrect. The word was {}.'.format(word))
A note on naming, unrelated to your issue: Python convention for naming variables and functions is to use lowercase_names_with_underscores for everything, unless the code is mimicking an existing API that uses a different convention. Use CapitalizedNames for classes, and ALL_CAPS for constants.
The most important thing though, is to to be consistent. Your current code seems to have a mix of underscores, capitalization and other styles without any logic to it. Pick one style (even if it's not the one I described in the previous paragraph) and stick to it. (This can be hard to do if your instructor is inconsistent in naming style. Alas there may not be much you can do about that.)

Python 3.6.1: Code does not execute after a for loop

I've been learning Python and I wanted to write a script to count the number of characters in a text and calculate their relative frequencies. But first, I wanted to know the length of the file. My intention is that, while the script goes from line to line counting all the characters, it would print the current line and the total number of lines, so I could know how much it is going to take.
I executed a simple for loop to count the number of lines, and then another for loop to count the characters and put them in a dictionary. However, when I run the script with the first for loop, it stops early. It doesn't even go into the second for loop as far as I know. If I remove this loop, the rest of the code goes on fine. What is causing this?
Excuse my code. It's rudimentary, but I'm proud of it.
My code:
import string
fname = input ('Enter a file name: ')
try:
fhand = open(fname)
except:
print ('Cannot open file.')
quit()
#Problematic bit. If this part is present, the script ends abruptly.
#filelength = 0
#for lines in fhand:
# filelength = filelength + 1
counts = dict()
currentline = 1
for line in fhand:
if len(line) == 0: continue
line = line.translate(str.maketrans('','',string.punctuation))
line = line.translate(str.maketrans('','',string.digits))
line = line.translate(str.maketrans('','',string.whitespace))
line = line.translate(str.maketrans('','',""" '"’‘“” """))
line = line.lower()
index = 0
while index < len(line):
if line[index] not in counts:
counts[line[index]] = 1
else:
counts[line[index]] += 1
index += 1
print('Currently at line: ', currentline, 'of', filelength)
currentline += 1
listtosort = list()
totalcount = 0
for (char, number) in list(counts.items()):
listtosort.append((number,char))
totalcount = totalcount + number
listtosort.sort(reverse=True)
for (number, char) in listtosort:
frequency = number/totalcount*100
print ('Character: %s, count: %d, Frequency: %g' % (char, number, frequency))
It looks fine the way you are doing it, however to simulate your problem, I downloaded and saved a Guttenberg text book. It's a unicode issue. Two ways to resolve it. Open it as a binary file or add the encoding. As it's text, I'd go the utf-8 option.
I'd also suggest you code it differently, below is the basic structure that closes the file after opening it.
filename = "GutenbergBook.txt"
try:
#fhand = open(filename, 'rb')
#open read only and utf-8 encoding
fhand = open(filename, 'r', encoding = 'utf-8')
except IOError:
print("couldn't find the file")
else:
try:
for line in fhand:
#put your code here
print(line)
except:
print("Error reading the file")
finally:
fhand.close()
For the op, this is a specific occasion. However, for visitors, if your code below the for state does not execute, it is not a python built-in issue, most likely to be: an exception error handling in parent caller.
Your iteration is inside a function, which is called inside a try except block of caller, then if any error occur during the loop, it will get escaped.
This issue can be hard to find, especially when you dealing with intricate architecture.

Resources