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
Related
I do reverse string and input is The quick brow fox
def reverse_word(word):
for i in word:
re = (i[::-1])
print('Reversed words ==> '+ re )
def main():
word = input('Enter a line : ').split()
reverse_word(word)
main()
but my result is
Reversed words ==> ehT
Reversed words ==> kciuq
Reversed words ==> worb
Reversed words ==> xof
I want result like:
Reversed words ==> ehT kciuq worb xof
you can use end in print method
def reverse_word(word):
print('Reversed words ==> ', end='')
for i in word:
re = (i[::-1])
print(re, end=' ' )
def main():
word = input('Enter a line : ').split()
reverse_word(word)
main()
Can try this one :
def reverse_word(word):
print("Reversed words ==>", end="")
for i in word:
re = (i[::-1])
print(" " + re, end="")
def main():
word = input('Enter a line : ').split()
reverse_word(word)
main()
In order to get a single line output , you can have a global string out = "" To which you will concatenate your resulting words.
out += " " + re
Inside the for loop
And this can be printed right after the end of the loop.
out = ""
def reverse_word(word):
for i in word:
re = (i[::-1])
out += " " + re
print("Reversed Words ==> " + out)
def main():
word = input('Enter a line : ').split()
reverse_word(word)
main()
def reverse_word(word):
res = ""
for i in word:
re = (i[::-1])
res += " "+re
return 'Reversed words ==>'+ res
word = input('Enter a line : ').split()
print(reverse_word(word))
Believe this would have desired effect.
Not really a question asked so no need to explain it further. Keep it simple!
When you say word it looks like this is really a collection of words, so words is probably a better name, and each of those should probably be word rather than i.
def reverse_words(words):
for word in words:
re = (word[::-1])
print('Reversed words ==> '+ re )
def main():
words = input('Enter a line : ').split()
reverse_words(words)
main()
Now, we can use a generator expression to generate the reversed word for each word.
(word[::-1] for word in words)
And let's join those with a space.
' '.join(word[::-1] for word in words)
And putting it into a function, using an f-string to print it:
def reverse_words(words):
print(f"Reversed words ==> {' '.join(word[::-1] for word in words)}")
Alternatively, we can use reversed.
def reverse_words(words):
print(f"Reversed words ==> {' '.join(''.join(reversed(word)) for word in words)}")
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 = ''
I'm trying to make a simple script that seraches for a designated .txt file for the last word that starts with a capital letter and returns it. If there are no words that start with a capital letter, it returns an empty string.
This is what I have tried so far:
def find_last_capitalised(file_name):
with open(file_name) as wordfile:
text_str = wordfile.read()
word_list = text_str.split()
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for word in word_list:
if word.rfind(upper):
return word
else:
return " "
but this isn't working.
I also tried this:
with open(file_name) as wordfile:
text_str = wordfile.read()
word_list = text_str.split()
for word in word_list:
if word_list[-1].isupper():
return word_list[-1]
else:
return " "
Any help?
Others provided you with various method for doing your task. I want to explain why your 1st method do not work as intended:
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if word.rfind(upper):
.rfind method of str is looking for position of last substring ABCDEFGHIJKLMNOPQRSTUVWXYZ inside word. I guess that your words do NOT contain such substring, in which case .rfind returns -1, which according to rules of Python evaluate to True (as it is not zero), so it would catch almost any word (it will give 0 or False only for words starting with ABCDEFGHIJKLMNOPQRSTUVWXYZ and containing only single ABCDEFGHIJKLMNOPQRSTUVWXYZ)
Fist of all, your algorithm would return the first capitlized word, not the last so there needs to be a little change in logic. Also the simplest way to check if word is capitalized is provided:
def find_last_capitalised(file_name):
with open(file_name) as wordfile:
text_str = wordfile.read()
word_list = text_str.split()
last_cap_word = " "
for word in word_list:
if word[0].isupper():
last_cap_word = word
return last_cap_word
Looks like you need reversed.
Ex:
def find_last_capitalised(file_name):
with open(file_name) as wordfile:
text_str = wordfile.read()
word_list = text_str.split()
for word in reversed(word_list): #reversed
if word[0].isupper():
return word
return " "
I did something like this.
import re
pattern = "[A-Z][a-zA-Z]+"
with open('input.txt', 'r') as file:
for el in reversed(file.readlines()):
res = re.findall(pattern, el)
if res:
print(res[-1])
def find_last_capitalised(word_list):
lastCapWord = " "
for word in word_list:
print(word)
if word[0].isupper():
lastCapWord = word
print('lastCapWord:', lastCapWord)
return lastCapWord
word_list = ['this', 'is', 'A', 'test']
find_last_capitalised(word_list)
Your algorithm is a little off. It doesn't go through each word in the list, instead it just returns based off the first word it sees. Assuming you make you make your word list into an array, the following code should work just fine.
You need are returning " " at first fail. That's why you don't get expected result.
def find_last_capitalised(file_name):
with open(file_name) as wordfile:
text_str = wordfile.read()
word_list = text_str.split()
for word in reversed(word_list):
if word[0].isupper():
return word
return ""
However if your file is much bigger, you might want to read file in a reverse order. Which will let you find what you looking for much easier.
import os
def find_last_capitalised(file_name):
with open(file_name) as wordfile:
wordfile.seek(0, os.SEEK_END)
position = wordfile.tell()
word = ''
while position >= 0:
qfile.seek(position)
next_char = qfile.read(1)
if next_char == " ":
if word[0].isupper():
return word
word = ''
else:
word += next_char
position -= 1
return ""
I suggest using similar approach to solve your problem.
You can try with reversed and is_upper keywords:
def find_last_capitalised(file_name):
with open(file_name) as wordfile:
text_str = wordfile.read()
word_list = text_str.split()
word_list = reversed(word_list)
for word in word_list:
if word[0].isupper():
return word
print(find_last_capitalised("demo.txt"))
def find_last_capitalised(file_name):
with open(file_name) as wordfile:
text_str = wordfile.read()
word_list = text_str.split(" ")
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for word in reversed(word_list):
if upper.rfind(word[0]) >= 0:
return word
return " "
Please try with the above code ... If its not working let me know here.
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