Hello I have written this code in order to translate user input in morses alphabet and write it in a file , but I have 1 problem: It doesn't have spaces between each letter.Thank you in advance I can re-explain the problem if needed.
import re
def txt_2_morse(msg):
morse = {
'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.',
'F':'..-.', 'G':'--.', 'H':'....', 'I':'..', 'J':'.---',
'K':'-.-', 'L':'.-..', 'M':'--', 'N':'-.', 'O':'---',
'P':'.--.', 'Q':'--.-', 'R':'.-.', 'S':'...', 'T':'-',
'U':'..-', 'V':'...-', 'W':'.--', 'X':'-..-', 'Y':'-.--',
'Z':'--..', '1':'.----', '2':'..---', '3':'...--', '4':'....-',
'5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.',
'0':'-----', ' ':'/'}
return "".join([morse.get(c.upper(), ' ') for c in msg])
while True:
user_input = input('Input your hidden message!')
regex_matcher= re.compile("/[a-z]+[A-Z]+[0-9]/g")
if (regex_matcher.search(user_input) == False ):
user_input
else:
f = open("myfile.txt", "w")
f.write(txt_2_morse(user_input + "\n"))
f.close()
break
How can i add space after each letter/number after its written in the file
since that code that generate the file body is
"".join([morse.get(c.upper(), ' ') for c in msg])
All you need to do is to use a space instead of empty string
" ".join([morse.get(c.upper(), ' ') for c in msg])
Related
I want to basically remove all the characters in delete list from the file (Line 11 to 15). What would be the neatest way to delete the words without making the code not neat. I am not sure whether to open the file again here which I know would not be the right way but I can't think of a different solution. Any help would be appreciated.
from os import write
import re
def readText():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt') as f:
print(f.read())
def longestWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r+') as f:
users_text = f.read()
#I want to basically remove all the char in delete list from the file. What would be the neatest way to delete the words without making the code not neat. I am not sure wether to open the file again here and re write it or what!
deleteList = ['!','£','$','%','^','&','*','()','_','+']
for line in f:
for word in deleteList:
line = line.replace(word, '')
longest = max(users_text.split(), key=len)
count_longest = str(len(longest))
print('The longest word in the file is: ' + long)
print('Thats a total of '+count_longest+' letters!')
def writeWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'w') as f:
users_text = input('Enter your desired text to continue. \n: ')
f.write(users_text)
f.close()
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r') as file:
print(file.read())
longestWord()
Had to re work it and implement it in a different def. Need to add relative paths and will be alot cleaner aswell.
from os import write
import re
def longestWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r+') as f:
users_text = f.read()
longest = max(users_text.split(), key=len)
count_longest = str(len(longest))
print('The longest word in the file is: ' + longest)
print('Thats a total of '+count_longest+' letters!')
def writeWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'w') as f:
users_text = input('Enter your desired text to continue. \n: ')
cleanText = re.sub('[^a-zA-Z0-9 \n\.]', ' ', users_text)
f.write(cleanText)
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r') as clean:
print('\nRemoved any illegal characters. Here is your text:\n\n' + cleanText + '\n')
f.close()
while True:
print("""
Welcome to Skies word text counter!
====================================================
""")
writeWord()
longestWord()
userDecide = input("""
====================================================
Would you like to enter new text and repeat?
Type 'yes' to continue else program will terminate.
====================================================
: """)
if not userDecide.lower == 'yes':
print('Application closing...')
exit()
I need to encrypt a message. The message follows, it is saved in a file named assignmenttest.txt
Hi my name is Allie
I am a Junior
I like to play volleyball
I need the program to encrypt each line and keep it's format so that So, I wrote the following program:
fileInputName = input("Enter the file you want to encrypt: ")
key = int(input("Enter your shift key: "))
outputFileName = input("Enter the file name to write to: ")
fileInputOpen = open(fileInputName, "r")
message = fileInputOpen.read()
alphabet = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
shiftedStart = alphabet[len(alphabet) - key:]
shiftedEnd = alphabet[:len(alphabet) - key]
shiftedAlphabet = shiftedStart + shiftedEnd
encryptedMessage = ""
for character in message:
letterIndex = message.split("\n")
letterIndex = alphabet.find(character)
encryptedCharacter = shiftedAlphabet[letterIndex]
#print( "{0} -> {1}".format(character, encryptedCharacter))
encryptedMessage += encryptedCharacter
print("The encrypted message is: {0}".format(encryptedMessage))
outputFile = open( outputFileName, "w")
print(encryptedMessage, file=outputFile)
outputFile.close()
print("Done writing encrypted message to file {0}".format(outputFileName))
I tried to use a split at \n, but the output is not formatted in three separate lines, instead it is all just one long string of encrypted letters.
Any ideas on how to split the encrypted message at the correct spot and have it display as such? I've tried multiple split methods and none have worked. Thank you so much.
As the other answers have said, you can replace
fileInputOpen = open(fileInputName, "r")
message = fileInputOpen.read()
with
with open(fileInputName, "r") as f:
messages = f.readlines()
This way, messages will be a list of strings, where each string is the text from a single line in your input file. Then, with some slight modifications to your loop over each character in messages, you can encrypt each string from your messages list. Here, I replaced your encryptedMessage with currentEncryptedMessage and added encryptedMessages, a list that keeps track of the encrypted version of each string in messages.
encryptedMessages = []
currentEncryptedMessage = ""
for message in messages:
for character in message:
... # same as code provided
currentEncryptedMessage += encryptedCharacter
encryptedMessages.append(currentEncryptedMessage)
When writing to your file, you can iterate through each element in encryptedMessages to print line-by-line.
with open( outputFileName, "w") as outputFile:
for message in encryptedMessages:
print(message, file=outputFile)
And so your output text file will preserve the line breaks from your input file.
Instead of splitting at '\n', you can append all the characters in message that are not in alphabet to encryptedMessage when you encounter one.
for character in message:
if !(character in alphabet):
encryptedMessage += character
continue # this takes back to begin of the loop
letterIndex = alphabet.find(character)
encryptedCharacter = shiftedAlphabet[letterIndex]
#print( "{0} -> {1}".format(character, encryptedCharacter))
encryptedMessage += encryptedCharacter
Try changing:
message = fileInputOpen.read()
to
message = fileInputOpen.readlines()
This will make your file reads handle the file line by line. This will allow you to do your processing on a line by line basis first. Beyond that, If you want to encrypt each character, you'll need another for loop for the characters.
Instead of reading the file all at once. Read the lines individually.
f = open("file.txt")
for i in f.readlines():
print (i)
You'll have to loop each line and every character you want to
un-shift;
The script should only un-shift characters present in alphabet;
Checking for file existence is also a must or you may get errors if it doesn't exist.
with open... is the recommended way of reading and writing files in python.
Here's an approach:
import os
import string
fileInputName = input("Enter the file you want to encrypt: ")
while not os.path.exists(fileInputName):
fileInputName = input("{} file doesn't exist.\nEnter the file you want to encrypt : ".format(fileInputName))
key = int(input("Enter your shift key (> 0): "))
while key < 1 :
key = int(input("Invalid shift key value ({}) \nEnter your shift key (> 0): ".format(key)))
fileOutputName = input("Enter the file name to write to: ")
if os.path.exists(fileOutputName) :
ow = input("{} exists, overwrite? (y/n): ".format(fileOutputName))
if not ow.startswith("y"):
fileOutputName = input("Enter the file name to write to: ") # asks for output filename again
alphabet = string.ascii_letters + " "
shiftedStart = alphabet[len(alphabet) - key:]
shiftedEnd = alphabet[:len(alphabet) - key]
shiftedAlphabet = shiftedStart + shiftedEnd
with open(fileOutputName, "a") as outputFile: # opens out file
with open(fileInputName, "r") as inFile: # opens in file
for line in inFile.readlines(): # loop all lines in fileInput
encryptedCharacter = ""
for character in line: # loop all characters in line
if character in alphabet: # un-shift only if character is present in `alphabet`
letterIndex = alphabet.find(character)
encryptedCharacter += shiftedAlphabet[letterIndex]
else:
encryptedCharacter += character # add the original character un-shifted
outputFile.write("{}".format(encryptedCharacter)) # append line to outfile
This program is supposed to replace the letters ö,ä,õ,ü with different letters. After completing one row it produces an empty row and I don't know why. I have tried to understand it for some time, but I couldn't really understand why it doesn't give me desired output.
f = input("Enter file name: ")
file = open(f, encoding="UTF-8")
for sentence in file:
sentence = sentence.upper()
for letter in sentence:
if letter == "Ä":
lause = sentence.replace(letter, "AE")
elif letter == "Ö" or täht == "Õ":
lause = sentence.replace(letter, "OE")
elif letter == "Ü":
lause = sentence.replace(letter, "UE")
print(sentence)
Reading each line in includes the trailing newline. Your print() also includes a newline so you will get an empty row. Try print(sentence, end='') as follows:
filename = input("Enter file name: ")
with open(filename, encoding="UTF-8") as f_input:
for sentence in f_input:
sentence = sentence.upper()
for letter in sentence:
if letter == "Ä":
lause = sentence.replace(letter, "AE")
elif letter == "Ö" or täht == "Õ":
lause = sentence.replace(letter, "OE")
elif letter == "Ü":
lause = sentence.replace(letter, "UE")
print(sentence, end='')
Note: using with open(... will also automatically close your file afterwards.
You might also want to consider the following approach:
# -*- coding: utf-8
filename = input("Enter file name: ")
replacements = [('Ä', 'AE'), ('ä', 'ae'), ('Ö', 'OE'), ('ö', 'oe'), ('Õ', 'OE'), ('õ', 'oe'), ('Ü', 'UE'), ('ü', 'ue')]
with open(filename, encoding='utf-8') as f_input:
text = f_input.read()
for from_text, to_text in replacements:
text = text.replace(from_text, to_text)
print(text)
This does each replacement on the whole text rather than line by line. It also preserves the case.
I won't fix your program, just try to answer why it doesn't do what you are expecting:
The program doesn't run: in line 14 the variable "täht" might be a typo, supposed to be "letter"
You store the result of replace() in variable "lause" but never use it
by default print() adds "\n" at the end, but you can override it (see help(print) in the python shell)
import os
searchquery = 'word'
with open('Y:/Documents/result.txt', 'w') as f:
for filename in os.listdir('Y:/Documents/scripts/script files'):
with open('Y:/Documents/scripts/script files/' + filename) as currentFile:
for line in currentFile:
if searchquery in line:
start = line.find(searchquery)
end = line.find("R")
result = line[start:end]
print result
f.write(result + ' ' +filename[:-4] + '\n')
Now this works well to search for "word" and prints everything after word up until an "R" providing that it is on the same line. However if the "R" is on the line it won't print the stuff before it.
eg:
this should not be printed!
this should also not be printed! "word" = 12345
6789 "R" After this R should not be printed either!
In the case above the 6789 on line 3 will not be printed with my current. However i want it to be. How do i make python keep going over multiple lines until it reaches the "R".
Thanks for any help!
It is normal that it does not print the content on the next line because you are searching for the word on one line. A better solution would be as follows.
import os
searchquery = 'word'
with open('Y:/Documents/result.txt', 'w') as f:
for filename in os.listdir('Y:/Documents/scripts/script files'):
with open('Y:/Documents/scripts/script files/' + filename) as currentFile:
content = ''.join([line for line in currentFile])
start = content.find(searchquery)
end = content.find("R")
result = content[start:end].replace("\n", "")
print result
f.write(result + ' ' +filename[:-4] + '\n')
Please be advised, this will work only for a single occurence. You will need to break it up further to print multiple occurences.
I am trying to use binary search to check the spelling of words in a file, and print out the words that are not in the dictionary. But as of now, most of the correctly spelled words are being printed as misspelled (words that cannot be find in the dictionary).
Dictionary file is also a text file that looks like:
abactinally
abaction
abactor
abaculi
abaculus
abacus
abacuses
Abad
abada
Abadan
Abaddon
abaddon
abadejo
abadengo
abadia
Code:
def binSearch(x, nums):
low = 0
high = len(nums)-1
while low <= high:
mid = (low + high)//2
item = nums[mid]
if x == item :
print(nums[mid])
return mid
elif x < item:
high = mid - 1
else:
low = mid + 1
return -1
def main():
print("This program performs a spell-check in a file")
print("and prints a report of the possibly misspelled words.\n")
# get the sequence of words from the file
fname = input("File to analyze: ")
text = open(fname,'r').read()
for ch in '!"#$%&()*+,-./:;<=>?#[\\]^_`{|}~':
text = text.replace(ch, ' ')
words = text.split()
#import dictionary from file
fname2 =input("File of dictionary: ")
dic = open(fname2,'r').read()
dic = dic.split()
#perform binary search for misspelled words
misw = []
for w in words:
m = binSearch(w,dic)
if m == -1:
misw.append(w)
Your binary search works perfectly! You don't seem to be removing all special characters, though.
Testing your code (with a sentence of my own):
def main():
print("This program performs a spell-check in a file")
print("and prints a report of the possibly misspelled words.\n")
text = 'An old mann gathreed his abacus, and ran a mile. His abacus\n ran two miles!'
for ch in '!"#$%&()*+,-./:;<=>?#[\\]^_`{|}~':
text = text.replace(ch, ' ')
words = text.lower().split(' ')
dic = ['a','abacus','an','and','arranged', 'gathered', 'his', 'man','mile','miles','old','ran','two']
#perform binary search for misspelled words
misw = []
for w in words:
m = binSearch(w,dic)
if m == -1:
misw.append(w)
print misw
prints as output ['mann', 'gathreed', '', '', 'abacus\n', '']
Those extra empty strings '' are the extra spaces for punctuation that you replaced with spaces. The \n (a line break) is a little more problematic, as it is something you definitely see in external text files but is not something intuitive to account for. What you should do instead of for ch in '!"#$%&()*+,-./:;<=>?#[\\]^_``{|}~': is just check to see if every character .isalpha() Try this:
def main():
...
text = 'An old mann gathreed his abacus, and ran a mile. His abacus\n ran two miles!'
for ch in text:
if not ch.isalpha() and not ch == ' ':
#we want to keep spaces or else we'd only have one word in our entire text
text = text.replace(ch, '') #replace with empty string (basically, remove)
words = text.lower().split(' ')
#import dictionary
dic = ['a','abacus','an','and','arranged', 'gathered', 'his', 'man','mile','miles','old','ran','two']
#perform binary search for misspelled words
misw = []
for w in words:
m = binSearch(w,dic)
if m == -1:
misw.append(w)
print misw
Output:
This program performs a spell-check in a file
and prints a report of the possibly misspelled words.
['mann', 'gathreed']
Hope this was helpful! Feel free to comment if you need clarification or something doesn't work.