How can I translate words with a python script? - python

So we have to translate numbers from English to German. I feel I am doing it all wrong because I get no
output when I test my code.
#!/usr/bin/env python3
import sys
english = sys.stdin.read().split()
num = {}
with open("translation.txt") as f:
data = f.read().split("\n")
i = 0
while len(data[i]) < 0:
n = data[i].split()
n1 = n[0]
n2 = n[1]
if n1 not in num:
num[n1] = n2
i = i + 1
i = 0
while i < len(english):
n = english[i]
if n in num:
print(num[n])
i = i + 1
Please help. Am I even getting the code to open the text file? the text file contains numbers translated from English to German
Example of translation.txt
one: eins
two: zwei
three: drei
four: vier
five: funf
six: sechs
seven: sieben
eight: acht
nine: neun
ten: zehn

Well, your code had some major logical errors. First of all, a comparison was wrong for the loops. You also split the line but you left : in the keys. Also checking if the word already exists is not necessary, but I left it as you wrote. I also added two side translation just in case you will need it.
Here is my implementation of the problem:
#!/usr/bin/env python3
import sys
english = sys.stdin.read().split()
num = {}
with open("translation.txt") as f:
data = f.read().split("\n")
i = 0
while i < len(data):
n = data[i].split()
print(n)
n1 = n[0].replace(':', '')
n2 = n[1]
if n1 not in num and n2 not in num:
num[n1] = n2
num[n2] = n1
i = i + 1
print(num['one'])
print(num['eins'])

You read inputs from standard input via sys.stdin.read(). This requires reading ALL characters until an EOF is met, which would happen only if:
An EOF is entered via the keyboard (Ctrl-D for Unix-based systems and Ctrl-Z for Windows);
The input is redirected from another stream that ends with an EOF, such as a file stream.
If the input is entered line by line via the keyboard, the output won't be seen until an EOF is seen. If it is desired that the output is shown immediately after one line of input, input() should be used instead of sys.stdin.read().
Other issues have been explained in #Raguel's answer.

Here we have a major issue with application logic, as were mentioned in previous answers:
First of all, we need to load dictionary - our resource to operate.
Second, we can start the translation, for example word-by-word from continues user input
The compact solution (require python 3.8):
#!/usr/bin/env python3
with open("translation.txt", "r") as f:
dictionary = { k: v.strip() for k, v in [line.split(":") for line in f.readlines()]}
while word:=input("Word to translate: "):
try:
print(dictionary[word])
except KeyError:
print(f"No translation found for the word: {word}")

Related

Why is my function not prompting me to enter input?

I’m using Python IDE 3. My goal is this: If I have a string of text, ‘ABCDEFGHIJKL’, I want to sort it into groups, like three groups (‘ADGJ’,’BEHK’,’CFIL’). I require input for this, but the prompts aren’t showing up and I can’t type in input. Here’s my code:
#data
code_text = input('Text: ').lower()
code_skip = int(input('Shift length: '))
code_list = []
#function
def countSkip(text, shift, listt):
i = 0
group = 1
if group <= shift:
for e in text:
#make sure the set starts at the right place
if e.index()+1 < group:
pass
elif shift != 0:
if i = shift:
listt.append(e)
i = 0
i += 1
else:
listt.append(e)
group += 1
Calling the function
countSkip(code_text, code_shift, code_list)
There's a few things stopping your code from working that people have pointed out in the comments. Instead of trying to dissect your code and get that to work, I wrote a much more concise function that will get you the results you're after
def text_splitter(input_text, set_length):
num_sets = int(len(input_text)/set_length)
split_text = ["".join([input_text[(n * num_sets) + m] for n in range(set_length)]) for m in range(num_sets)]
return split_text
text_to_split = input('Text: ').lower()
len_set = int(input('Set Length: '))
text_list = text_splitter(text_to_split, len_set)
Sorry I was struggling to name the variables in an effective manner but the function above uses a list expression to get you the results you need. Keep in mind that if you use say a 7 letter string and ask for sets of length 2, the last letter won't be appended. However this shouldn't be too hard to check and correct. For example you could add this code to the function or around the initial input for the set length:
while len(input_text) % set_length != 0:
set_length = int(input("The text is length " + str(len(input_text)) + " please enter a different set length: "))

Checking if characters in a file can be integers

So in a Python assignment I have to write a decoder for an mtf encoded file, which is made up of hex characters and words. In my decoder I'm reading the .mtf file char by char and checking whether or not its a letter or a hex number and I can't seem to make it work. I've erased the majority of my code to start fresh but here's the basic framework:
f = open(str(sys.argv[1]), "r")
new_f = str(sys.argv[1])
new_f = new_f[:len(new_f)-3]+ "txt"
f_two = open(new_f, "w")
myList = []
word = ""
words = []
index = 0
while True:
value = None
c = f.read(1)
if not c:
break
try:
value = int(c)
except ValueError:
word = word + c
I apologize for the horribly written code and any mistakes I may have made while writing this, this is all still relatively new to me.
Thank you!
When you read from a file in Python, you're reading in strings. Strings also have a method called isdigit() which tells you if the one character is a digit or not.
while c:
c = f.read(1)
if c.isdigit():
myList.append(c)
If you're checking for hex characters (0-9, A-F), you would have to build your own checking function. Something like this:
def is_hex(n):
return n.isdigit() or ("A" <= n.upper() <= "F")

Input error in Python (EOF error)

I have this error in many solutions.I went through many answers on this topic but could not resolve the problem.I could only figure out that problem could be in taking input from a single input file where the whole input string is taken in one input call and displays EOF error on second raw input call.
def change(a,b,l):
alist = []
blist = []
for m in range(0,26):
alist.append(0)
blist.append(0)
for i in a:
alist[l[i]] += 1
for j in b:
blist[l[j]] += 1
common = 0
for i in range(0,26):
dif = (alist[i] - blist[i])
if (dif != alist[i]):
common += min(alist[i],blist[i])
total = (min(len(a),len(b)) - common) + abs(len(a) - len(b))
return total
test = int(raw_input())
ans = []
l = {}
for i in range(65,91):
l[chr(i)] = i - 65
for i in range(0,test):
a = str(raw_input())
b = str(raw_input())
ans = ans + [change(a,b,l)]
for j in ans:
print j
It would be a great help if someone could describe how to take input at above mentioned multiple times from a single input file.
Especially if you want input from files, and not a terminal, you can use the readline() function of file objects. Example:
import sys
def test(f):
num = int(f.readline())
for i in range(num):
a = int(f.readline())
b = int(f.readline())
print a, b
if __name__ == '__main__':
test(sys.stdin)
You might also want to actually use the end of file as a marker for end of input. In your example you may not for instance require to get the number of records in the first line, but just go on until you hit EOF.

Use variables for input and output PyAIML

I have included the below source which is my full project at the moment. What I have working so far is a terminal interface where I input a phrase and it then takes the response (from the AIML database), takes each letter and one-by-one plays the .mp3 sound for that letter to make a BASIC translator (R2D2 here). There are a couple of problems. The first is that it works fine for the first time I enter in a phrase (in that it translates the output perfectly), but then encounters an Index error and the terminal closes. (see figure 1) I don't know what is wrong with it, but suspect it may be something faulty with my while loop.
The other issue I have is that I plan to use this with a speech interface, so I say something, it's run through a STT engine which then outputs what I said as a string. I want that string to then be given as the input to PyAIML to then get a response from and translate it as it does in this program. The problem I have is how to make a variable which can then be used as input to PyAIML. Any ideas how I'd do this?
import aiml
import os
import time
def translate():
if char == 'a':
os.system("start a.mp3")
elif char == 'b':
os.system("start b.mp3")
#This continues for all the letters of the alphabet - you get the idea
else:
time.sleep(0.1),
k = aiml.Kernel()
k.learn("std-startup.xml")
k.respond("load aiml b")
while True:
string = k.respond(raw_input("> "))
input = string.lower()
numChar = len(input)
n = 0
m = 0
char = input[n]
while m < numChar:
translate()
time.sleep(0.25),
n = n + 1
char = input[n]
m = m + 1
Note: the response does work; it comes up with this error after the output has been translated.
Your code is stepping through each character individually, when you should just step through the string (and it will return back each character).
Python is a bit different in that traditional "find the length, set a counter to 0, until count is less than the length, fetch by the counter" pattern is not required.
You can also optimize your code a bit:
import aiml
import os
import time
character_mappings = {'a': 'a.mp3', 'b': 'b.mp3'}
def speak(char):
out = character_mappings.get(char)
if out:
os.system('start {}'.format(out))
else:
time.sleep(0.1)
k = aiml.Kernel()
k.learn("std-startup.xml")
k.respond("load aiml b")
while True:
text = k.respond(raw_input("> ")) # "string" is a built-in
for char in text.lower():
speak(char) # translate is also a built-in
time.sleep(0.25)
Check n before char = input[n] because n is bigger then length of input
--
Or change
n = n + 1
char = input[n]
into
char = input[n]
n = n + 1
EDIT:
I don't know what you try to do but this
numChar = len(input)
n = 0
m = 0
char = input[n]
while m < numChar:
translate()
time.sleep(0.25),
n = n + 1
char = input[n]
m = m + 1
can be done this way
for char in input:
translate()
time.sleep(0.25)
but I would do this
def translate(letter):
if letter == 'a':
os.system("start a.mp3")
if letter == 'b':
os.system("start b.mp3")
# rest of code
else:
time.sleep(0.1)
for char in input:
translate(char)
time.sleep(0.25)
or even this
def translate(letter):
if letter in 'abcde': # all accepted letters
os.system("start "+letter+".mp3")
else:
time.sleep(0.1)

Reading input from Python and print out in while loop

I wonder how I can translate the following C++ code to Python code.
int n;
while (cin >> n)
cout << n <<endl;
My guess is it would be something like this
import sys
while n = raw_input():
print n + "\n"
but it doesn't work... Please help me. Thank you.
perhaps something like this:
import sys # why?
n = "string"
while n:
n = raw_input()
print n + '\n'
However
while n = raw_input(): # incorrect.
This won't work because:
n is not defined
In any case, to test equality you should generally use ==, though not in this particular case, as it would mean basically, while n is equal to empty string( '' )
example:
>>> raw_input() == ''
True
That's because n = raw_input() in Python does not return a value whereas cin >> n in C++ does. (This saves the programmers from the most common error of replacing == with =)
You can try something like.
n = raw_input("Enter Something: ")
while n:
print n
n = raw_input("Enter Something: ")
Test Run :
>>>
Enter Something: Monty
Monty
Enter Something: Python
Python
Enter Something: Empty Line Next
Empty Line Next
Enter Something:
P.S- There's no need of the import sys in this case (if you're not using it anywhere else in your code). Also, print statement automatically moves the cursor to the next line, so you need not add \n in this case.

Categories