I am trying to pass words to a function that will be checked with words in a seperate file. It only passes the last word created from the first file and not each word. So I think how it should work is as soon as it creates a word it should pass that word to the function then check it and return the results, but I'm confused as to how. If the word matches a word in the second file it should print the word then a 0 or if it doesn't match a word then print 1.
import sys
argc = len(sys.argv)
cmdlength = argc - 1
if cmdlength != 2:
print ("Usage error, expected 2 args got " + str(cmdlength))
exit()
else:
word = ""
with open(sys.argv[1],"r") as fh:
while True:
ch=fh.read(1)
if not ch:
print(word)
print("End of file")
break
if ch == ' ':
print(word)
word = ''
else:
word += ch
def check_word(word):
count = 0
count2 = 0
with open(sys.argv[2],"r") as fh2:
lines = fh2.readlines()
for line in lines:
if word in line:
print(word , ": " , "0")
count += 1
else:
print(word, ": " , "1")
count += 1
check_word(word)
When you call the check_word function, you are doing it once after the while loop ends, for that reason only the last word is passed to the function. You should call the function after each word is armed, in your case, when ch == ' ':
if ch == ' ':
print(word)
check_word(word)
word = ''
Related
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()
import string
def main():
filename = input("Enter the name of a file to translate into Pig Latin: ")
vowels = ['a', 'e', 'i', 'o', 'u','A','E','I','O','U']
regFile = open((filename), 'r')
Output = open('Output.txt', 'w')
for line in regFile.readlines():
pigList = line.split()
t = translate(pigList, vowels)
w = write(t, Output)
regFile.close()
input ("Press ENTER to continue: ")
def translate(pigList, vowels):
PigList2 = []
for word in pigList:
if word[-1] in string.punctuation:
actual_word = word[:-1]
ending = word[-1]
else:
actual_word = word
ending = ""
if word[0] in vowels:
PigList2.append(actual_word + "-yay" + ending)
else:
PigList2.append(actual_word[1:] + "-" + actual_word[0] + "ay" + ending)
return PigList2
def write(pigList, Output):
print(" ".join(pigList))
main()
I believe this has fixed my errors. Thank you for the help. I know have the translator working correctly and translating all the lines at once instead of one line at a time.
You're almost there. I just used used the punctuation check to split up your word into the actual word and the punctuation and then append the '-' before the first letter rather than with the "ay".
def translate(pigList, vowels):
PigList2 = []
for word in pigList:
if word[-1] in string.punctuation:
actual_word = word[:-1]
ending = word[-1]
else:
actual_word = word
ending = ""
if word[0] in vowels:
PigList2.append(actual_word + "-yay" + ending)
else:
PigList2.append(actual_word[1:] + "-" + actual_word[0] + "ay" + ending)
return PigList2
I'm currently trying to get my program to accept multiple lines, but at the moment it's picking the last line, and just converting that to pig latin. I believe it's this part of the code, but I don't know exactly what to change.
def pig_word(string):
for line in text:
line = line.split()
lines = []
for line in string.split('\n'):
new_string = ""
for word in line.split():
first_letter = word[0]
if first_letter in vowels:
new_string += word + "way" + " "
else:
new_string += word[1:] + first_letter + "ay" + " "
global new_string
lines.append(new_string)
The complete code is:
vowels = ("A", "a", "E", "e", "I", "i", "O", "o", "U", "u")
# Functions
def pig_word(string):
for line in text:
line = line.split()
lines = []
for line in string.split('\n'):
new_string = ""
for word in line.split():
first_letter = word[0]
if first_letter in vowels:
new_string += word + "way" + " "
else:
new_string += word[1:] + first_letter + "ay" + " "
global new_string
lines.append(new_string)
def line_counter(s):
line_count = 0
for _ in s.split("\n"):
line_count += 1
return line_count
def word_counter(line):
word_count = 0
list_of_words = line.split()
word_count += len(list_of_words)
return word_count
# File path conversion
text = raw_input("Enter the path of a text file: ")
file_path = open(text, "r")
out_file = open("pig_output.txt", "w")
s = file_path.read()
pig = pig_word(s)
out_file.write(str(new_string)+ "\n")
out_file.write("\n")
linecount = line_counter(s)
wordcount = word_counter(s)
file_path.close()
out_file.close()
# Results
print "\n\n\n\nTranslation finished and written to pig_output.txt"
print "A total of {} lines were translated successfully.".format(linecount)
print "A total of {} words were translated successfully.".format(wordcount)
print "\n\n\n\n"
The input file contains:
Pig latin
I dont know what is wrong with this
Random testing
Randomly typing
Output file is:
andomlyRay ypingtay
In your code there are several inconsistencies and weird constructs; just looking at the most obvious issues, change your pig_word as:
def pig_word(string):
lines = []
for line in string.split('\n'):
new_string = ""
for word in line.split():
first_letter = word[0]
if first_letter in vowels:
new_string += word + "way" + " "
else:
new_string += word[1:] + first_letter + "ay" + " "
lines.append(new_string)
return lines
then at the bottom of the script, where you save the output:
out_file.write('\n'.join(pig))
There would be other things to discuss on your code, but this should fix the biggest issue.
You use the global variable new_string to print out the result. This variable contains only one line, therefore, at the end of the for-loop, the last line. Return the variable lines, which is at the moment unused, and use this list to print out every line:
def pig_word(string):
lines = []
for line in string.split('\n'):
new_line = []
for word in line.split():
first_letter = word[0]
if first_letter in vowels:
new_line.append(word + "way")
else:
new_line.append(word[1:] + first_letter)
lines.append(' '.join(new_line))
return lines
For a basic computer science class in python we're writing a program that reads in a file, translates the file to pig latin and writes the translation in a new file, and counts the number of lines and words translated.
file_path = raw_input("Enter a file pathway: ")
f_input = file(file_path, "r")
f_output = file("pig_output.txt","w")
vowels = ("a","e","i","o","u","A","E","I","O","U")
def piglat_trans():
line_count = 0
word_count = 0
for line in f_input:
words = line.split(" ")
pig_line = ""
line_count += 1
for word in words:
word = word.strip("\n")
word_count += 1
if word[0] in vowels:
pig_word = word + "way"
elif word[0] not in vowels and word[1] not in vowels and len(word)>1:
pig_word = word [2:len(word)] + word[0] + word[1] + "ay"
else:
pig_word = word[1:len(word)] + word[0] + "ay"
pig_line += pig_word + " "
f_output.write(pig_line + "\n")
print "Translation finished and written pig_output.txt"
print "A total of " + str(line_count) + " lines were translated successfully."
print "A total of " + str(word_count) + " words were translated successfully."
piglat_trans()
f_input.close()
f_output.close()
The program works fine, but I'm supposed to make the line/word count and the printing parts separate functions from the translator itself. How would I do this?
Thanks for the help!
** Edit: also I've been having a problem with spaces and tabs with the translation and it returns:
line 25, in piglat_trans if word[0] in vowels:
IndexError: string index out of range
Well, since this is a homework, I won't write code.
Looks like your key logic lies in the most inner for-loop, where you take a word and pig_latinify it.
And after that, you just need a mapper function for mapping every word of the source to a pig-latinified version of the text. This function can also count the number of lines.
And, try to make your file handlers short lived, and use a context manager(with statement in Python).
Here is what I'd do:
def pigify(word):
....
return pig
def pigify_text(text):
...
pig_words = map(pigify, words)
...
return (pig_text, word_count, line_count)
with open(infile) as f:
text = f.read()
pig, wc, lc = pigify_text(text)
with open(outfield, "w") as f:
f.write(pig)
print wc
print lc
The problem I am trying to solve is reading in a file in that contains a list of words. Then counting the number of vowels in each word and display each word in a table along with the number of its vowels and the total vowels in the word, and at the end display the total number of vowels in all of the words.
I am trying to solve the problem by reading the file in through a for loop and creating a dictionary that is associated with every word like
mississippi['a_count' : 0, 'e_ocunt' : 0, 'i_count' : 4 ,'o_count' : 0, 'u_count' : 0, 'y_count' : 0]
My problem is that I am not sure how to create the dictionaries as the variable changes due to a loop. I am just ending up with empty dictionaries.
here's a screenshot of my output http://imgur.com/mksgdTc
my test code in the file is Mississippi California Wisconsin all on different lines.
try:
word_file = open("vowel.txt", "r")
count = 0
dic = {}
a_count = 0
e_count = 0
i_count = 0
o_count = 0
u_count = 0
y_count = 0
total_count = 0
#this establishes the top of the table
print('Number','{:>8}'.format('word'),'{:>8}'.format('A'),'{:>4}'.format('E'),'{:>4}'.format('I'),'{:>4}'.format('O'),'{:>4}'.format('U'),'{:>4}'.format('Y'),'{:>8}'.format('Total'))
print("__________________________________________________________")
for word in word_file:
count+=1
word = {}
print(word)
word_a_count = 0
word_e_count = 0
word_i_count = 0
word_o_count = 0
word_u_count = 0
word_y_count = 0
word_total_count = 0
for letters in word:
print(letters)
if letters.lower() == "a":
a_count+= 1
total_count += 1
word_a_count +=1
word['a_count'] = word_a_count
if letters.lower() == "e":
e_count+= 1
total_count += 1
word_e_count +=1
word['e_count'] = word_e_count
if letters.lower() == "i":
i_count+= 1
total_count += 1
word_i_count +=1
word['i_count'] = word_i_count
if letters.lower() == "o":
o_count+= 1
total_count += 1
word_o_count +=1
word['o_count'] = word_o_count
if letters.lower() == "u":
u_count+= 1
total_count += 1
word_u_count +=1
word['u_count'] = word_u_count
if letters.lower() == "y":
y_count+= 1
total_count += 1
word_y_count +=1
word['y_count'] = word_y_count
print('Totals','{:>8}'.format(' '),'{:>8}'.format(word['a_count']),'{:>4}'.format\
(word['e_count']),'{:>4}'.format(word['i_count']),'{:>4}'.format\
(word['o_count']),'{:>4}'.format(word['u_count']),'{:>4}'.\
format(word['y_count']))
#this creates the bottom barrier of the table
print("__________________________________________________________")
#code for totals print
print('Totals','{:>8}'.format(' '),'{:>8}'.format(a_count),'{:>4}'.format(e_count),'{:>4}'.format(i_count),'{:>4}'.format(o_count),'{:>4}'.format(u_count),'{:>4}'.format(y_count),'{:>6}'.format(total_count))
except IOError:
print("The file does not seem to exists. The program is halting.")
Focus on this section -- word is re-assigned as an empty dict on every iteration of the loop:
for word in word_file:
count+=1
word = {}
However, commenting word = {} out now throws an error when the first vowel is read from file (since now the dict isn't empty). Remember that word is the current line in the text file that you are iterating over, so word['u_count'] = word_u_count is interpreted as an instruction to change a character in the string. Python strings are immutable, so an error is thrown.
Your program is much longer than it needs to be - when you notice repetition in your code consider refactoring to take advantage of loops and iteration, to make your program more concise. You could separate all the logic for counting the letters in a word into one procedure:
def countletters(word, letterstocount):
count = {}
word = word.lower()
for char in word:
if char in letterstocount:
if char in count:
count[char] += 1
else:
count[char] = 1
return count
#example call
vowels = "aeiou"
print(countletters('Arizona', vowels))
which you then call for each word in your file.
In Python 2 I'd do something like this...
#! /usr/bin/env python
'''
Count vowels in a list of words & show a grand total
Words come from a plain text file with one word per line
'''
import sys
vowels = 'aeiouy'
def make_count_dict():
''' Create a dict for counting vowels with all values initialised to 0 '''
return dict(zip(vowels, (0,)*len(vowels)))
def get_counts(d):
return ' '.join('%2d' % d[k] for k in vowels)
def count_vowels(wordlist):
hline = '_'*45
print '%3s: %-20s: %s' % ('Num', 'Word', ' '.join('%2s' % v for v in vowels))
print hline
total_counts = make_count_dict()
for num, word in enumerate(wordlist, start=1):
word_counts = make_count_dict()
for ch in word.lower():
if ch in vowels:
word_counts[ch] += 1
total_counts[ch] += 1
print '%3d: %-20s: %s' % (num, word, get_counts(word_counts))
print hline
print '%-25s: %s' % ('Total', get_counts(total_counts))
def main():
fname = len(sys.argv) > 1 and sys.argv[1]
if fname:
try:
with open(fname, 'r') as f:
wordlist = f.read().splitlines()
except IOError:
print "Can't find file '%s'; aborting." % fname
exit(1)
else:
wordlist = ['Mississippi', 'California', 'Wisconsin']
count_vowels(wordlist)
if __name__ == '__main__':
main()