How do I print a sentence for an assigned output/input? - python

I have a code that allows a user to choose between 3 options
Ie; Beginner: 1, Intermediate: 2 and Advanced: 3.
However, I'm wanting to generate a paragraph that's assigned to each of the 3 options.
For example
If the user has entered 1 for Beginner, the output will follow with "Hi Beginner! We are going to learn about ....."
The code I've tried thus far is just using the print(" ")option followed by
if f==0:
print("You have entered " + str(inp) + ": " + out).
However, as I'm writing a long paragraph, the output is messy.

Well, i think that you're printing a line without using "\n" in your print text, that's why the output will be always a entire line.
You can use "\n" to write different lines:
print("This is a line\nNow this is other")
Or you can use triple quotes:
print("""This is a line
Now this is other""")

Related

Printing over 50 emoji's in one line forces unwanted whitespace (Python) (Visual Studio Code)

Currently working on making a python boardgame representation in the terminal using emoji's, but as soon as my emoji print gets past 50 emoji's, it forces whitespace. This does not happen when printing a string of 50 normal characters or a string of equally lengthed characters. When I do even more emoji's, things sometimes get even weirder with question mark emoji's (see
Terminal picture).
s = "\U0001F7E8"
print("50:")
print(s*50)
print("\n51:")
print(s*51)
print("\n60:")
print(s*60)
print("\n70:")
print(s*70)
print("\n80:")
print(s*80)
print("\n220:")
print(s*220)
print("what I'm currently working on")
#I made string_representation with a lot of code above which I don't feel like matters for my question, so I left that out.
print(string_representation)
print("sadsfdgfhgjgfdssadsfdgfhgjgfdssadsfdgfhgjgfdssadsfdgfhgjgfdssadsfdgfhgjgfdssadsfdgfhgjgfdssadsfdgfhgjgfdssadsfdgfhgjgfds")
I tried locally, it's the problem with the python multiple print(*) and the emoji you take('\U0001F7E8'). You'd better switch to some other emojis.
# s = '\U0001F7E8'
s = '🐍'
# s = '🟨'
s5 = s*5
print(s*60)
for i in range(60):
print(s, end="")
print()
for x in range(6):
print(s*10, end="")
print()
print(s5*12)
print()
for i in range(12):
print(s5, end="")
print()
for x in range(4):
print(s5*3, end="")
print()
Try to print them in one print condition like this
print("50:", s*50, "\n51", s*51, "\n51")
and so on maybe thats your problem
because in the string representation you added them in one print condition

Trying to search for follow up questions in a text file

I have a piece of code that will search through a transcript of a call between a marketer and a customer. The code scans through the transcript line by line searching for a phrase specified in an external txt file, if it finds a match, it prints the entire line the match is on, followed by the next line, which is the response.
I've developed a bit of code that will identify if 'yes' has been said to one question, which will lead to more follow up questions, however, I cannot get it to loop through the rest of the script searching for these follow up questions after the line?
Could anyone give me a hand?
I have the following code:
with open ('/Users/owenmurray/Desktop/untitled folder/untitled folder/transcribe.txt') as my_new_file:
contents = my_new_file.read()
partner_file = open('/Users/owenmurray/Desktop/untitled folder/untitled folder/P.txt')
with open('/Users/owenmurray/Desktop/untitled folder/untitled folder/follow_up_question.txt') as follow_up_question_file:
follow_up = follow_up_question_file.read()
partners = partner_file.readlines()
# Converts it to a list
lines = contents.split("\n")
follow_up_list = follow_up.split("\n")
for p in partners:
try:
output = None
for index, line in enumerate(lines):
if p.strip() in line:
output = index
break
if output:
print ("\n" + lines[output] + "\n")
print("-------------------------------------------------------------")
print("\n" + lines[output +1] + "\n")
if "yes" in lines[output +1].lower() or "yeah" in lines[output + 1].lower():
print("-------------------------------------------------------------")
print ("\n" + lines[output +2] + "\n")
try:
for follow in follow_up_list():
if follow in lines[output+2].lower():
True
print("-------------------------------------------------------------")
print ("\n" + lines[output +3] + "\n")
break
except (ValueError):
print("Nothing found")
break
except:
pass
An example of my transcript can be found here:
https://paste.pythondiscord.com/obucaweyuc.py
My p.txt can be found here:
have you spoken with a ARM partner in the last six months
And my follow_up_questions.txt has:
did you talk about similar issues?
However the current output only displays:
ch_0 : have you spoken with a ARM partner in the last six months
about having a discussion about how ARM those, um, quality
security could benefit you guys?
ch_1 : Yeah, we have
ch_0 : Oh, okay and did you talk about similar issues?
I have cleaned up your code a bit just to try to simplyfy the problem. I have included the output it produces, as per your comment it gives the line after
with open('transcribe.txt') as t_file, open('p.txt') as p_file, open('follow_up_question.txt') as f_file:
t_lines = t_file.readlines()
f_lines = f_file.readlines()
p_lines = p_file.readlines()
for p_line in p_lines:
for index, line in enumerate(t_lines):
if p_line.strip() in line:
print(f'{t_lines[index]}{"-"*30}\n{t_lines[index + 1]}', end='')
if "yes" in t_lines[index + 1].lower() or "yeah" in t_lines[index + 1].lower():
print(f'{"-"*30}\n{t_lines[index + 2]}', end='')
for follow in f_lines:
if follow in t_lines[index + 2].lower():
print(f'{"-"*30}\n{t_lines[index + 3]}', end='')
OUTPUT
ch_0 : have you spoken with a ARM partner in the last six months about having a discussion about how ARM those, um, quality security could benefit you guys?
------------------------------
ch_1 : Yes, we have
------------------------------
ch_0 : Oh, okay and did you talk about similar issues?
------------------------------
ch_0 : Okay, Uh, would you be willing to, um, have a discussion with ARM partner? Um, it's project making business sense
However just for your reference the issue in your code was this line
for follow in follow_up_list():
follow_up_list is a python list and is not callable so you need to drop the parentheses
for follow in follow_up_list:

python3 looping a list with 1 variable at a time

still learning python, so I apologize if this question is sloppy.
I am familiar with loops, and looping through a file. However, I have not found the correct referance to looping a file, storing the variable and calling that variable into another function, and maintain the increment.
Using pyautogui and pywinauto.
Written form:
get names.txt file with list of 20 or so names (the list changes so keeping track of line count seems reasonable)
Split the text of the file for parsing.
in example:
setup of name.txt file.
Mark
James
Sam
Steve
.
def do(name):
# open and read file
fname = 'names.txt'
for name in (open(fname, "r")).readlines():
print("Found: " + name)
more(name)
Output:
['Mark', 'James', 'Sam', 'Steve]
def more(name):
pyautogui.moveT0(600,511)
pyautogui.click()
pyautogui.typewrite(a[0])
pyautogui.moveTo(699,412)
pyautogui.press("enter")
confirm(name)
def confirm(name)
pic = pyscreenshot.grab(bbox=(8,11,211,728))
f = "images/active"
g = "images/go"
pic.save(f + a + ".png")
pic.save(g + ".png")
b = Image.open("images/go.png"
text = image_to_search(b, lang='eng')
if text == name:
print("Success")
else:
print("Mismatch")
This is the part where the function will end and start back at the top of the program increment our digit and applying the next name for searching. The confirm program (already completed) takes an image of the search field and passes the text. If the name is equal to the name in the list (a[0]) then we move onto the next name.
Bringing up another question of how to "call a variable from a function"?
Thanks a lot!
First off, your code is rife with indentation, syntactical and logcial errors, you have to fix those before you apply the below
def file_stuff(a, fname):
for name in (open(fname, "r")).readlines():
print ("Found: " + name)
gui_stuff(name)
def gui_stuff(name):
pyautogui.moveT0(600,511)
pyautogui.click()
pyautogui.typewrite(name) # ATTENTION, please confirm if this is how the typewriter fn works. you are only printing the first char
pyautogui.moveTo(699,412)
pyautogui.press("enter")
confirm(name)
Please fix the if-else indentation in your confirm function, and other dangling indentation references in your code

Python 3: How to ignore line breaks when using input()

while count != 5:
input_text = input("Please insert a number of lines of text \n")
if count != 5:
print("Count is " + str(count))
For the code above, when prompted to supply input, if I paste in a text with multiple line breaks. The code will run for the number of line breaks! I just want it to run ONCE for the entire text.
Can anyone help?
You can use sys.stdin.read() but it will require you to manually send the EOT character:
>>> import sys
>>> x = sys.stdin.read()
the quick brown fox
jumped over the lazy
dog
>>> print(x)
the quick brown fox
jumped over the lazy
dog
>>>
Notice, at the end after I pasted I use Enter and then ctrl-D.
I didn't find the exact answer for you question however i did notice that when you copy in multiple lines of text in the shell it only assigns the first line of text to input_text, then runs again and assigns the second line to input_text, runs agains and third line of input_text. You see.
I think the input statement is not ment for multiple lines though you can sure find some workaround.
This code here shows how each time the loop is ran the variable changes too the next line of that you copied into shell:
count = 0
while True:
count += 1
input_text = input("Please insert a number of lines of text \n")
print("Count is " + str(count))
print("what the variable is set to first time its running the loop: ",input_text,"\n")

Bell character as Fields separator in Python print output

I am fairly new to Python and need a little help here.
I have a Python script running on Python 2.6 that parses some JSON.
Example Code:
if "prid" in data[p]["prdts"][n]:
print data[p]["products"][n]["prid"],
if "metrics" in data[p]["prdts"][n]:
lenmet = len(data[p]["prdts"][n]["metrics"])
i = 0
while (i < lenmet):
if (data[p]["prdts"][n]["metrics"][i]["metricId"] == "price"):
print data[p]["prdts"][n]["metrics"][i]["metricValue"]["value"]
break
Now, this prints values in 2 columns:
prid price
123 20
234 40
As you see the fields separator above is ' '. How can I put a field separator like BEL character in the output?
Sample expected output:
prid price
123^G20
234^G40
FWIW, your while loop doesn't increment i, so it will loop forever, but I assume that was just a copy & paste error, and I'll ignore it in the rest of my answer.
If you want to use two separate print statements to print your data on one line you can't avoid getting that space produced by the first print statement. Instead, simply save the prid data until you can print it with the price in one go using string concatenation. Eg,
if "prid" in data[p]["prdts"][n]:
prid = [data[p]["products"][n]["prid"]]
if "metrics" in data[p]["prdts"][n]:
lenmet = len(data[p]["prdts"][n]["metrics"])
i = 0
while (i < lenmet):
if (data[p]["prdts"][n]["metrics"][i]["metricId"] == "price"):
price = data[p]["prdts"][n]["metrics"][i]["metricValue"]["value"]
print str(prid) + '\a' + str(price)
break
Note that I'm explicitly converting the prid and price to string. Obviously, if either of those items is already a string then you don't need to wrap it in str(). Normally, we can let print convert objects to string for us, but we can't do
print prid, '\a', price
here because that will give us an unwanted space between each item.
Another approach is to make use of the new print() function, which we can import using a __future__ import at the top of the script, before other imports:
from __future__ import print_function
# ...
if "prid" in data[p]["prdts"][n]:
print(data[p]["products"][n]["prid"], end='\a')
if "metrics" in data[p]["prdts"][n]:
lenmet = len(data[p]["prdts"][n]["metrics"])
i = 0
while (i < lenmet):
if (data[p]["prdts"][n]["metrics"][i]["metricId"] == "price"):
print(data[p]["prdts"][n]["metrics"][i]["metricValue"]["value"])
break
I don't understand why you want to use BEL as a separator rather than something more conventional, eg TAB. The BEL char may print as ^G in your terminal, but it's invisible in mine, and if you save this output to a text file it may not display correctly in a text viewer / editor.
BTW, It would have been better if you posted a Minimal, Complete, Verifiable Example that focuses on your actual printing problem, rather than all that crazy JSON parsing stuff, which just makes your question look more complicated than it really is, and makes it impossible to test your code or their modifications to it.

Categories