import sys
import pickle
import string
def Menu():
print ("\n***********MENU************")
print ("0. Quit")
print ("1. Read text file")
print ("2. Display counts")
print ("3. Display statistics of word lengths")
print ("4. Print statistics to file")
def Loop():
choice = -1
while choice !=0:
Menu()
choice = (int(input("Please choose 1-4 to perform function. Press 0 to exit the program. Thank you. \n")))
if choice == 0:
print ("Exit program. Thank you.")
sys.exit
elif choice == 1:
user_File = ReadTextFile()
elif choice == 2:
DisplayCounts(user_File)
elif choice == 3:
DisplayStats(user_File)
elif choice == 4:
PrintStats(aDictionary)
else:
print ("Error.")
def ReadTextFile():
print "\n"
while True:
InputFile = input("Please enter a file name (NOTE: must have quotation marks around name and extension): ")
if (InputFile.lower().endswith('.txt')):
break
else:
print("That was an incorrect file name. Please try again.")
continue
return InputFile
def DisplayCounts(InputFile):
print "\n"
numCount = 0
dotCount = 0
commaCount = 0
lineCount = 0
wordCount = 0
with open(InputFile, 'r') as f:
for line in f:
wordCount+=len(line.split())
lineCount+=1
for char in line:
if char.isdigit() == True:
numCount+=1
elif char == '.':
dotCount+=1
elif char == ',':
commaCount+=1
print("Number count: " + str(numCount))
print("Comma count: " + str(commaCount))
print("Dot count: " + str(dotCount))
print("Line count: " + str(lineCount))
print("Word count: " + str(wordCount))
def DisplayStats(InputFile):
print "\n"
temp1 = []
temp2 = []
lengths = []
myWords = []
keys = []
values = []
count = 0
with open(InputFile, 'r') as f:
for line in f:
words = line.split()
for word in words:
temp2.append(word)
temp1.append(len(word))
for x in temp1:
if x not in lengths:
lengths.append(x)
lengths.sort()
dictionaryStats = {}
for x in lengths:
dictionaryStats[x] = []
for x in lengths:
for word in temp2:
if len(word) == x:
dictionaryStats[x].append(word)
for key in dictionaryStats:
print("Key = " + str(key) + " Total number of words with " + str(key) + " characters = " + str(len(dictionaryStats[key])))
return dictionaryStats
def PrintStats(aDictionary):
print "\n"
aFile = open("statsWords.dat", 'w')
for key in aDictionary:
aFile.write(str(key) + " : " + str(aDictionary[key]) + "\n")
aFile.close()
Loop()
There's something with that last function that is really tripping me up. I keep getting errors. I know aDictionary is not defined but I do not even know what to define it as! Any of you guys have an idea? Thanks.
with open("some_file.txt","W") as f:
print >> f, "Something goes here!"
its hard to say without your errors. .. but you almost certainly need to have aDictionary defined
also probably something like
def DisplayCounts(InputFile):
print "\n"
numCount = 0
dotCount = 0
commaCount = 0
lineCount = 0
wordCount = 0
with open(InputFile, 'r') as f:
for line in f:
wordCount+=len(line.split())
lineCount+=1
for char in line:
if char.isdigit() == True:
numCount+=1
elif char == '.':
dotCount+=1
elif char == ',':
commaCount+=1
return dict(numbers=numCount,
comma=commaCount,
dot=dotCount,
line=lineCount,
word=wordCount)
result = DisplayCounts("someinput.txt")
print result
Related
I'm trying to add user entered data to a tuple, then write that tuple on a line in my text file. I'm doing something wrong because only the last call is added to the txt file. Here's my functions:
def write_to_file(tuple1):
with open('student_info.txt', 'w') as f:
f.write(' '.join(x for x in tuple1))
f.write("\n")
def get_student_info(student_name):
tuple1 = ()
tuple1 = tuple1 + (student_name,)
print("\nScores for " + student_name)
print("Enter a test score (or enter Stop to stop):")
count = 2
test_score = input("Test score 1: ")
tuple1 = tuple1 + (test_score,)
while not test_score == "stop" and not test_score == "Stop":
test_score = input("Test score " + str(count) + ": ")
count = count + 1
tuple1 = tuple1 + (test_score,)
last_item = len(tuple1) - 1
tuple1 = tuple1[:last_item]
write_to_file(tuple1)
def read_from_file():
with open('student_info.txt', 'r') as f:
f_contents = f.read()
print(f_contents, end=" ")
And here's my calls in the main section:
open("student_info.txt", "w").close()
student_name = ""
get_student_info("Jenny: ")
get_student_info("Dave: ")
get_student_info("Sammy: ")
get_student_info("Brooke: ")
read_from_file()
My student_info.txt just ends up reading "Brooke:" and then the data added to the tuple on the last call.
If you want to append to a file you need to change the ‘w’ to an ‘a’ for append when you want to write to the file.
I was instructed to have a user input at least 8 words into a list and then perform various manipulations to the data within the list. One of the manipulations it asks me to do is to create a loop that makes every other letter in the strings capitalized (hElLo WoRlD.) For better readability, I left out the other manipulations that I have done to the code.
import sys
def main():
words = []
wordCount = 0
userWord = input("Enter at least 8 words or 'bye' to leave the program: ").split(' ')
while True:
if len(userWord)<8:
print("Please print at least 8 words, try again.")
sys.exit()
elif wordCount >= 8 and userWord[wordCount] != 'bye':
words.append(userWord[wordCount])
wordCount = wordCount + 1
else:
break
every_other (userWord)
def every_other(words):
words6 = words.copy()
st = ""
for i in range(len(words6)):
if (i%2) == 0:
st += words6[i].upper()
else:
st += words6[i]
print ('This is your list with every other letter capitalized: ', words6)
return st
main()
I am not getting any error messages but the code doesn't seem to be running starting at def every_other.
You'll have to print the function every_other as it returns a string:
import sys
def main():
words = []
wordCount = 0
userWord = input("Enter at least 8 words or 'bye' to leave the program: ").split(' ')
while True:
if len(userWord)<8:
print("Please print at least 8 words, try again.")
sys.exit()
elif wordCount >= 8 and userWord[wordCount] != 'bye':
words.append(userWord[wordCount])
wordCount = wordCount + 1
else:
break
print('This is your list with every other letter capitalized: ', every_other(userWord))
def every_other(words):
words6 = words.copy()
st = ""
for i in range(len(words6)):
if (i%2) == 0:
st += words6[i].upper()
else:
st += words6[i]
return st
#print ('This is your list with every other letter capitalized: ', words6) # This will never run as the function has already returned
main()
If you want to capitalize every second character:
import sys
def main():
words = []
wordCount = 0
userWord = input("Enter at least 8 words or 'bye' to leave the program: ").split(' ')
while True:
if len(userWord)<8:
print("Please print at least 8 words, try again.")
sys.exit()
elif wordCount >= 8 and userWord[wordCount] != 'bye':
words.append(userWord[wordCount])
wordCount = wordCount + 1
else:
break
print('This is your list with every other letter capitalized: ', every_other(userWord))
def every_other(words):
st = ""
new_st = ""
for w in words:
st+=w
print(str(st))
for count, val in enumerate(st):
if (count % 2) == 0:
val = val.upper()
new_st+=val
return new_st
main()
I created this code that encrypts text but when it tries to decrypt I get a:
builtins.ValueError: chr() arg not in range(0x110000)
Any help in making the decryption code work properly would be much appreciated!
input1 = input("enter key word: ")
input2 = input1[:1]
key = ord(input2)
num_count = 32
dic= {}
while num_count <= 126:
resultant = float(num_count*key*565)
dic[num_count] = resultant
num_count += 1
string = input("Please enter text: ")
num_list = ""
for i in (string):
number = int(ord(i))
value = (dic[number])
number_value = str(value)
final_value = number_value+" "
num_list += final_value
print("Encrypted text is", num_list)
num_count3 = 0
decrypt_text = ""
string_len = len(num_list)
characters = []
localChar = ""
for i in num_list:
if i != " ":
localChar = localChar + i
elif i == " ":
characters.append(localChar)
localChar = ""
num_count3 = 0
list_len = len(characters)
while num_count3 < list_len:
value = float(characters[num_count3])
valuel = int(value/key/54734)
value2 = round(value)
de_char = chr(value2)
decrypt_text += de_char
num_count3 += 1
print(decrypt_text)
going to be honest, code was all over. But I hope this helps.
Issue:
num_count3 = 0 first instance not use
string_len = len(num_list) not used
int(value/key/54734) should be round(value/key/565) < your issue +
value2 = round(value) should be value2 = int(valuel)
And lots of clean up + Functions are great!
def encrypt(key, input1):
num_count = 32
dic = {i:float(i*key*565) for i in range(num_count,127)}
string = input("Please enter text: ")
num_list = ' '.join([str(dic[ord(i)]) for i in string])
print("Encrypted text is", num_list)
return num_list
def decrypt(key, num_list):
characters = num_list.split()
decrypt_text = ""
num_count3 = 0
list_len = len(characters)
while num_count3 < list_len:
value = float(characters[num_count3])
valuel = (value/key/565)
value2 = int(round(valuel))
de_char = chr(value2)
decrypt_text += de_char
num_count3 += 1
print(decrypt_text)
if __name__ == "__main__":
input1 = input("enter key word: ")
key = ord(str(input1[:1]))
print key
result = encrypt(key, input1)
decrypt(key, result)
the error is when I enter d, and Enter a sentence: David, y r u l8
David,why\nare\nyou\nlate\n , but I need it to return David, why are you late
def update_dictionary(fileName,dictionary):
try:
a = open(fileName)
except IOError:
print( fileName,"does not exist.")
print("The dictionary has",len(dictionary),"entries.")
return dictionary
with a:
print(fileName,"loaded successfully.")
for word in a:
c,b = word.split(",")
dictionary[c] = b
print("The dictionary has",len(dictionary),"entries.")
return dictionary
def deslang(filename,dic):
x = ""
words = filename.split(" ")
for i in range(len(words)):
if words[i] in dic:
words[i] = dic[words[i]]
for i in range(len(words)-1):
x = x + words[i] + " "
x = x + words[len(words) -1]
return x
def main():
name = {}
while 1:
u_input = input("Would you like to (a)dd words to the dictionary, (d)e-slang a sentence, or (q)uit?: ")
if u_input == "q":
break
if u_input == "a":
fileName = ""
while len(fileName) == 0:
fileName = input("Enter a filename: ")
name = update_dictionary(fileName,name)
if u_input == "d":
sentence = ""
while len(sentence) == 0:
sentence = input("Enter a sentence: ")
print(deslang(sentence, name))
if name =="main":
main()
You need to strip the newlines off each of the dictionary lines. In other words:
for word in a:
c,b = word.rstrip().split(",")
dictionary[c] = b
When you iterate a file like for word in a:, you get a string for each line in the file, including the newline at the end. So, your dictionary ends up full of entries like 'y': 'why\n' instead of 'y': 'why'.
You can strip the trailing newline from word.split(",") by calling str.strip.
word.strip().split(",")
You can also use read() to load the contents of the file which doesn't include newlines.
Code:
import os, csv
def menu():
print("Welcome to da sporty ting" + "\n" + "Menu options: " + "\n")
print("1 - Run the code")
print("2 - Exit")
menu_choice = int(input("Enter choice: "))
while menu_choice not in (1, 2):
menu_choice = int(input("Error, try again: "))
if menu_choice == 1:
finding_file()
elif menu_choice == 2:
exit()
def finding_file():
print("\n")
print("Text file options" + "\n")
print("1 - testfile 1" + "\n" + "2 - testfile 2" + "\n" + "3 - Other")
txt_menu_option = int(input("Enter choice: "))
print("\n")
while txt_menu_option not in (1, 2, 3):
txt_menu_option = input(input("Error, try again: "))
if txt_menu_option == 1:
filename = "Test1_Votes.txt"
pass
elif txt_menu_option == 2:
filename = "Test2_Votes.txt"
pass
elif txt_menu_option == 3:
filename = str(input("Enter name of txt file (don't include .txt at he end) : "))
filename = filename + ".txt"
file_exists = os.path.exists(filename)
if file_exists == False:
print("File does not exist, returning to menu")
menu()
pass
file_validity(filename)
def file_validity(filename):
f = open(filename, 'r+') # opening file in read/write mode
inv_lines_cnt = 0
valid_list = [0, 0, 1, 2, 3] # sorted list of valid values
lines = f.read().splitlines()
f.seek(0)
f.truncate(0) # truncating the initial file
for l in lines:
if sorted(map(int, l.split(','))) == valid_list:
f.write(l + '\n')
else:
print(l + " is a invalid line")
inv_lines_cnt += 1
print("There were {} invalid line/lines.".format(inv_lines_cnt))
calculate_quota(filename)
def calculate_quota(filename):
f = open(filename, 'r+')
lines = f.readlines()
print("Calculate quota " + str(lines))
seats = 2
line_count = 0
for line in lines:
line_count += 1
quota = 0
quota == int((line_count / (seats + 1)) + 1)
print(quota)
quota_required(quota, lines)
def quota_required(quota, lines):
for line in lines:
lines.rstrip(',')
lines.rstrip('\n')
print(lines)
candidate_fp_votes = [0,0,0,0,0]
for line in lines:
for i in range(5):
if line[i] == 1:
print ("if working")
candidate_fp_votes[i] += 1
print (candidate_fp_votes)
print (candidate_fp_votes)
Text file sample:
1,2,3,0,0
0,0,3,2,1
1,0,0,3,2
1,0,0,2,3
0,1,2,3,0
Currently I have a problem where after file_validity(), the text file just appears to have loaded up as empty as when I re-open the file in the next function, it prints lines as empty. file_validity() just deletes the file, and rewrites the valid votes. As you can see I have tried to find out where the trouble lies. I believe the truncate and seek functions seem to be causing some trouble but I am not sure if this is true. And if it were to be the case, how to fix it.
Any help?
Thanks in advance.