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
Related
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
In Python3 I must create two functions, substitutionEncrypt and substitutionDecrypt.
substitutionEncrypt must be revised so that it removes all spaces of plain text before being encrypted and that it will generate a cipher key from a password.(Call genKeyFromPass). psw will replace key as a parameter in the function header.
substitutionDecrypt will have two parameters(cipherText, psw)
I have been given the following codes. it should return the original plainText with spaces removed.
Finally, write a top-level function, main. main should (a) use Python’s built-in input function to get a string to encrypt and a password; (b) call substitutionEncrypt to encrypt the input string; (c) print the value returned by substitutionEncrypt; (d) call substitutionDecrypt to convert the value returned by substitutionEncrypt back to
plaintext; (e) print the value returned by substitutionDecrypt.
Note: subEncrypt and subDecrypt will need to call genKeyFromPass, which call removeDupes and removeMatches. I have been given the codes below.
defSubstitutionEncrypt(plainText, key):
alphabet = "abcdefghijklmnopqrstuvwxyz "
plainText = plainText.lower()
cipherText = " "
for ch in plainText:
idx = alphabet.find(ch)
cipherText = cipherText + key[idx]
return cipherText
def removeDupes(myString):
newStr = " "
for ch in myString:
if ch not in newStr:
newStr = newStr + ch
return newStr
def removeMatches(myString, removeString):
newStr = " "
for ch in myString:
if ch not in removeString:
newStr = newStr + ch
return newStr
def genKeyFromPass(password):
key = 'abcdefghijklmnopqrstuvwxyz'
password = removeDupes(password)
lastChar = password[-1]
lastIdx = key.find(lastChar)
afterString = removeMatches(key[lastIdx+1:], password)
beforeString = removeMatches(key[:lastIdx], password)
key = password + afterString + beforeString
return key
From this code I have created:
def substitutionEncrypt(plainText, psw):
alphabet = "abcdefghijklmnopqrstuvwxyz "
newStr = plainText.lower()
cipherText = " "
genKeyFromPass(newStr)
for ch in newStr:
idx = alphabet.find(ch)
cipherText = cipherText + genKeyFromPass(psw)[idx]
return cipherText.replace(" ","")
def genKeyFromPass(psw):
key = 'abcdefghijklmnopqrstuvwxyz'
psw = removeDupes(psw)
lastChar = psw[-1]
lastIdx = key.find(lastChar)
afterString = removeMatches(key[lastIdx+1:], psw)
beforeString = removeMatches(key[:lastIdx], psw)
key = psw + afterString + beforeString
return key
def removeDupes(myString):
newStr = " "
for ch in myString:
if ch not in newStr:
newStr = newStr + ch
return newStr
def removeMatches(myString, removeString):
newStr = " "
for ch in myString:
if ch not in removeString:
newStr = newStr + ch
return newStr
print(substitutionEncrypt('the quick brown fox', 'ajax'))
I get "nukobjdualhqguyhr" as an output.
The output examples are:
subEncrypt('the quick brown fox', 'ajax')
'qdznrexgjoltkblu'
subDecrypt('qdznrexgjoltkblu', 'ajax')
'thequickbrownfox'
What am I doing wrong with my code? I have been having trouble with calling a value from another function(calling key from genKeyFromPass). Its the line before the return statement in the substitutionEncrypt. Also, how would I go about the substitutionDecrypt? I've gotten this far:
def substitutionDecrypt(cipherText, psw):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
newStr = cipherText.lower()
plainText = " "
genKeyFromPass(cipherText)
for ch in cipherText:
idx = alphabet.find(ch)
return plainText.replace(" ","")
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