I have two output files which contain the same data (but different values). I'm using the following Python code to read them and return the data/value that I want:
upper = input("Enter file name (upper): ")
lower = input("Enter file name (lower): ")
fhr = open(upper)
for line in fhr:
word = line.rstrip().split()
if len(word) > 1 and word[1] == '1:47':
try:
sabs = word[2]
except:
continue
tot_upper = float(sabs)
print('Total upper:', tot_upper)
fhr.close()
fhr = open(lower)
for line in fhr:
word = line.rstrip().split()
if len(word) > 1 and word[1] == '1:47':
try:
sabs = word[2]
except:
continue
tot_lower = float(sabs)
print('Total lower:', tot_lower)
fhr.close()
Which gives me the output:
Total upper: x
Total lower: y
Is there are way that I can simplify the code such that I open the first file, run the code, then loop back to the beginning, open the second file and run the same code? Something like this:
upper = input("Enter file name (upper): ")
lower = input("Enter file name (lower): ")
file = [upper, lower]
for inp in file:
fhr = open(file)
for line in fhr:
word = line.rstrip().split()
if len(word) > 1 and word[1] == '1:47':
try:
sabs = word[2]
except:
continue
if inp == upper:
tot_upper = float(sabs)
print('Total upper:', tot_upper)
elif inp == lower:
tot_lower = float(sabs)
print('Total lower:', tot_lower
fhr.close()
I still want the same output:
Total upper: x
Total lower: y
You could do this:
for label in 'upper', 'lower':
# Ask for filename, using the label.
# Process the file.
# Print the result, using the label.
You probably need to use functions:
upper = input("Enter file name (upper): ")
lower = input("Enter file name (lower): ")
def f(name, s): # idk what is the function for so change to a custom name
fhr = open(name)
for line in fhr:
word = line.rstrip().split()
if len(word) > 1 and word[1] == '1:47':
try:
sabs = word[2]
except:
continue
tot = float(sabs)
print(f'Total {s}:', tot)
fhr.close()
f(upper, 'upper')
f(lower, 'lower')
Related
I know there are already countless clones of Wordle. Nevertheless I try to program my own version.
In the function is_real_word it should be checked whether the entered word of the user occurs in the word list. If so, the variable check = True.
However, the FOR loop is always exited when the counter is at 1.
The file "5_letter_words.txt" contains 3 entries: wetter, wolle, watte
And last but not least also the return value for eingabewort is sometimes NONE. And I don't know why?
import random
def word_list():
wordle = []
with open("5_letter_words.txt", "r") as file:
for line in file:
myTuple = line.strip()
wordle.append(myTuple)
return wordle
def random_word(wordlist):
return random.choice(wordlist)
def is_real_word(guess, wordlist):
for word in wordlist:
if guess == word:
return True
return False
def check_guess(guess, randomword):
randomword_tuple = []
guess_tuple = []
length = len(randomword)
output = ["-"] * length
for index in range(length):
if guess[index] == randomword[index]:
output[index] = "X"
randomword = randomword.replace(guess[index], "-", 1)
for index in range(length):
if guess[index] in randomword and output[index] == "-":
output[index] = "O"
randomword = randomword.replace(guess[index], "-", 1)
return ''.join(output)
def next_guess(wordlist):
guess = input('Please enter a guess: ')
guess = guess.lower()
valid = is_real_word(guess, wordlist)
if valid == False:
print('Thats not a real word!')
next_guess(wordlist)
else:
return guess
def play():
target = []
target = word_list()
zufallswort = str()
zufallswort = random_word(target)
eingabewort = next_guess(target)
print('Eingabewort: ', eingabewort)
print('Zielwort: ', zufallswort)
play()
Could you check if your function word_list returns the list?
You dont give a clear path, only the file name.
If it works, try:
def is_real_word(guess, wordlist):
for word in wordlist:
if guess == word:
check = 1
break
return check
I'm trying to use dictionary and some loops to figure out how many times a word was written and if user types in "quit" then the program should stop. This is what I have so far:
import string
text = open('text.txt', 'r')
val = dict()
for i in text:
i = i.strip().lower().split(" ")
print(i)
This is one approach to the problem:
with open('text.txt', 'r') as file:
data = file.read()
data = data.replace('\n', ' ')
data = data.split(' ')
while True:
counter = 0
search_term = input('Word: ')
if search_term == 'quit':
break
for word in data:
if word.lower() == search_term.lower() or word.lower() == search_term.lower() + '.':
counter += 1
if counter == 0:
print('None found!')
else:
print(f'Number of "{search_term}": {counter}')
def myNames():
names = []
while True:
a = input("Enter Name: ")
if a != "done":
names.append(a)
elif a == "done":
return names
def all_lengths(myNames):
num_of_strings = len(myNames)
total_size = 0
for item in myNames:
total_size += len(item)
ave_size = float(total_size) / float(num_of_strings)
print(ave_size)
all_lengths(myNames())
def longestWord(myNames):
count = 0
for i in myNames:
if len(i) > count:
count = len(i)
word = I
print ("the longest string is ", word)
how can I make it print the longest name that was inputted by the user for example: out of Samantha and John it would say that Samantha was the longest name
longestName = ""
for name in myNames:
if len(name) > len(longestName):
longestName = name
print("The longest name is", longestName)
This will check the length of each username, and if the name of that username is longer than the current longest username, it will replace it.
You already have the function for it.
Just need to call the function longestWord().
Write longestWord(myNames()) at the end of the program. Right after,
def longestWord(myNames):
count = 0
for i in myNames:
if len(i) > count:
count = len(i)
word = i # Need to type I in lower case
print ("the longest string is ", word)
Update: Since, you don't want the function to ask for names again, you can move the function calling longestWord()inside the above function where it calculates average, with the parameter as myNames i.e.
def myNames():
names = []
while True:
a = input("Enter Name: ")
if a != "done":
names.append(a)
elif a == "done":
return names
def longestWord(myNames):
count = 0
for i in myNames:
if len(i) > count:
count = len(i)
word = i
print ("the longest string is ", word)
def all_lengths(myNames):
num_of_strings = len(myNames)
total_size = 0
for item in myNames:
total_size += len(item)
ave_size = float(total_size) / float(num_of_strings)
print(ave_size)
longestWord(myNames) # Calling the function with already given names
all_lengths(myNames())
Hey guys so I have my program working to a certain extent. My program is suppose to check if there is an "A" in the user input and if done so it will swap that "A" with the next letter.
Here are the examples:
"tan" = "TNA"
"abracadabra" = "BARCADABARA"
"whoa" = "WHOA"
"aardvark" = "ARADVRAK"
"eggs" = "EGGS"
"a" = "A"
In my case this is what works and doesn't work:
Works:
tan to TNA
Doesn't work:
abracadabra = BARCADABAR
whoa = WHO
aardvark = ARADVRA
eggs = EGG
a =
a just equals nothing.
What I'm getting at is that the last character isn't printing and I'm not sure how to do so.
def scrambleWord(userInput):
count = 0
Word_ = ""
firstLetter_ = ""
secondLetter_ = ""
while count < len(userInput):
if count+1 >=len(userInput):
break #copy last character
firstLetter_ = userInput[count] #assigning first letter
secondLetter_ = userInput[count+1] #assigning next letter
if firstLetter_ == 'A' and secondLetter_ != 'A':
Word_ += (secondLetter_ + firstLetter_) #Swap then add both letters
count+=1
else:
Word_+=firstLetter_
count+=1
return Word_
def main():
userInput = input("Enter a word: ")
finish = scrambleWord(userInput.upper())
print(finish)
main()
Probably because you are just breaking without writing the userinput[count] into the word.
if count+1 >=len(userInput):
Word_ += userInput[count]
break #copy last character
This should help
I cant figure out why line 104 keeps returning invalid syntax, can someone please point me in the right direction? Does it have something to do with the way i used elif? Sorry if this is a newbie question!
Line 104 is the else statement in the for item in workingDict.keys() loops inside printGrammar
import sys
import string
from collections import defaultdict
#default length of 3
stringLength = 3
#get last argument of command line(file)
if len(sys.argv) == 1:
#get a length from user
try:
stringLength = int(input('Length? '))
filename = input('Filename: ')
except ValueError:
print("Not a number")
elif len(sys.argv) == 2:
#get a length from user
try:
stringLength = int(input('Length? '))
filename = sys.argv[1]
except ValueError:
print("Not a number")
elif len(sys.argv) == 3:
filename = sys.argv[2]
stringLength = sys.argv[1].split('l')[1]
else:
print("Invalid input!")
#get start symbol
with open(filename, "r") as grammar:
#read file
lines = grammar.readlines()
start = lines[0].split('=')[0]
start = start.replace(" ", "")
#checks
#print(stringLength)
#print(filename)
#print(start)
def str2dict(filename):
result = defaultdict(list)
with open(filename, "r") as grammar:
#read file
lines = grammar.readlines()
count = 0
#loop through
for line in lines:
#append info
line = line.rstrip()
result[line[0]].append(line.split('=')[1])
return result
workingDict = str2dict("Binary.txt")
print(workingDict)
def printGrammar(result):
sentenceList = []
workList = []
workList.append(start)
i = 0
firstNT = ""
#While the worklist is not empty:
while(len(workList) != 0):
#Get and delete one potential sentence s from the worklist.
symbol = workList.pop()
#If the | s | > N, continue.
if len(str(symbol).replace(" ", "")) > int(stringLength):
continue
else:
if str(symbol) in workingDict.keys():
#append the right derivation
for item in workingDict.get(symbol):
workList.append(list(item.replace(" ", "")))
#workList.append(str(workingDict.get(symbol)))
#add derivation
print(workingDict.keys())
#If s has no nonterminals, print s and continue.
for item in workingDict.keys():
print("test")
print(''.join(item))
if len(item) != 1:
continue
#if the element is in dictionary, dont print
elif ''.join(item) in workingDict.keys():
continue
print(symbol)
#if element is not in dictionary, print
else:
print("THIS IS A TERMINAL!!")
print(item)
#Choose the leftmost nonterminal NT.
print(workList)
#For all productions NT -> rhs:
#Replace NT in s with rhs; call it tmp.
#Store tmp on worklist.
return workList
print (printGrammar(workingDict))
You need to indent the line
print(symbol)
to the same level as continue.