How to send EOF indicator in console - python

For example, in C# Visual Studio if I input key combination Ctrl + Z it sends null to program and i use it in sentinel controlled loops for example in C#:
int total = 0;
string myInput = Console.ReadLine();
while (myInput != null)
{
total++;
myInput = Console.ReadLine();
}
Console.WriteLine(total);
Does this exist in python?

The easiest way of doing this in Python is to iterate over the input:
import sys
total = 0
for line in sys.stdin:
total += 1
print(total)
Or, if you really only want to count lines, you can write this shorter as
import sys
print(sum(1 for _ in sys.stdin))
This is using a so-called generator expression.

We can control it by EOF error exception, Simply type Ctrl + Z.
s = input()
i = 0
try:
while (True):
i += 1
s = input()
except EOFError:
print(i)

Related

How do you write a for(i = 0; i < listName.length; i++) on Python?

When doing programming on Java or C++, I use this form of a for loop:
for(i = 0; i < listName.length; i++)
It was giving red squiggly lines, so I did some search online. From what it looks, there isn't any existence of this for loop method in Python. I am resorting to the 'for letter in listName' and while loops, but I have not been able to substitute the above for loop in Java or C++ successfully. I have included code that gets half of the expected outcome.
Code:
email = input("Please enter an email: ")
letterList = [*email]
for letter2 in letterList:
if(letter2 == '.'):
for letter3 in letterList:
if(letter3 == '#'):
for letterStop in letterList:
if letterStop == '.':
break
else:
print(letterStop)
This is the output of the above code when jason#gmail.com gets entered:
j
a
s
o
n
#
g
m
a
i
l
Input:
jason#gmail.com
Expected output:
gmail
For loops exist in Python; they just have a different syntax.
for i in range(len(my_string_or_list)):
print(my_string_or_list[i])
for i,v in enumerate(my_string_or_list):
print(f"Index {i} contains {v}")
You can use the re module (regular expression) to extract the separate portions of an email address string into a list, and then get gmail from there:
import re
re.split(r"[#.]", "jason#gmail.com")[1] # 'gmail'
The loop you are talking about, "for(i = 0; i < listName.length; i++)", exists in Python, but it's a bit different. And it would go like this: "for i in range(len(yourlist):".
I see you are making a list out of string "letterList = [*email]", but you don't have to do that in Python. In Python, strings are iterable, so you can "for i in email:" and you would get every character.
The easiest way to get "gmail" out of the email address would be using the split() function like this.
email = "jason#gmail.com"
a = email.split("#")[1]
b = a.split(".")[0]
print(b)
In a variable, we split the email in two strings, one before # "jason" and one after "gmail.com". After that, we split "gmail.com" into two strings.

How can I translate words with a python script?

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}")

finding duplicates in a string at python 3

def find_duplicate():
x =input("Enter a word = ")
for char in x :
counts=x.count(char)
while counts > 1:
return print(char,counts)
I've got small problem in there i want to find all duplicates in string but this program give me only one duplicate ex: aassdd is my input function gave me only a : 2 but it need to be in that form a : 2 s : 2 d : 2 thanks for your answers.
return is a keyword that works more or less as immediately exit this function (and optionally carry some output with you). You thus need to remove the return statement:
def find_duplicate():
x =input("Enter a word = ")
for char in x :
counts=x.count(char)
print(char,counts)
Furthermore you also have to remove the while loop (or update the counter if you want to print multiple times), otherwise you will get stuck in an infinite loop since count is not updated and the test will thus always succeed.
Mind however that in this case a will be printed multiple times (in this case two) if it is found multiple times in the string. You can solve this issue by first constructing a set of the characters in the string and iterate over this set:
def find_duplicate():
x =input("Enter a word = ")
for char in set(x):
counts=x.count(char)
print(char,counts)
Finally it is better to make a separation between functions that calculate and functions that do I/O (for instance print). So you better make a function that returns a dictionary with the counts, and one that prints that dictionary. You can generate a dictionary like:
def find_duplicate(x):
result = {}
for char in set(x):
result[char]=x.count(char)
return result
And a calling function:
def do_find_duplicates(x):
x =input("Enter a word = ")
for key,val in find_duplicate(x).items():
print(key,val)
And now the best part is: you actually do not need to write the find_duplicate function: there is a utility class for that: Counter:
from collections import Counter
def do_find_duplicates(x):
x =input("Enter a word = ")
for key,val in Counter(x).items():
print(key,val)
This will help you.
def find_duplicate():
x = input("Enter a word = ")
for char in set(x):
counts = x.count(char)
while counts > 1:
print(char, ":", counts, end=' ')
break
find_duplicate()
Just because this is fun, a solution that leverages the built-ins to avoid writing any more custom code than absolutely needed:
from collections import Counter, OrderedDict
# To let you count characters while preserving order of first appearance
class OrderedCounter(Counter, OrderedDict): pass
def find_duplicate(word):
return [(ch, cnt) for ch, cnt in OrderedCounter(word).items() if cnt > 1]
It's likely more efficient (it doesn't recount each character over and over), only reports each character once, and uses arguments and return values instead of input and print, so it's more versatile (your main method can prompt for input and print output if it chooses).
Usage is simple (and thanks to OrderedCounter, it preserves order of first appearance in the original string too):
>>> find_duplicate('aaacfdedbfrf')
[('a', 3), ('f', 3), ('d', 2)]
def find_duplicate():
x = input("Enter a word = ")
dup_letters = []
dup_num = []
for char in x:
if char not in dup_letters and x.count(char) > 1:
dup_letters.append(char)
dup_num.append(x.count(char))
return zip(dup_letters, dup_num)
dup = find_duplicate()
for i in dup:
print(i)
This version should be fast as I am not using any library or more than one cycle, do you have any faster options?
import datetime
start_time = datetime.datetime.now()
some_string = 'Laptop' * 99999
ans_dict = {}
for i in some_string:
if i in ans_dict:
ans_dict[i] += 1
else:
ans_dict[i] = 1
print(ans_dict)
end_time = datetime.datetime.now()
print(end_time - start_time)
def find_duplicate():
x = input("Enter a word = ")
y = ""
check = ""
for char in x:
if x.count(char) > 1 and char not in y and char != check:
y += (char + ":" + str(x.count(char)) + " ")
check = char
return y.strip()

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