How to create a new line using tkinter.Text() - python

I've tried appending a '/n' as shown in the code below however the output is still just one block of text that extends from one line to the next, rather than creating a new line after each list entry like I want
final_presentation_text = ["You are " + diet, "Your calorie limit
is " + str(calorie_count),
"Your diet has " + str(calorie_number),
" Your carbs target is " +
str(carbs_target),
" Your diet has " + str(carbs_number)]
for lines in final_presentation_text:
final_presentation.insert(1.0, lines + '/n')

It's backslash ("\") and then "n" for a new line, i.e. "\n", not forward slash.

Related

When copying from terminal format is lost

I am trying to build an APA citation generator, asking the user for name of author, date, etc. And returning the correct reference structure. When it comes to citing a book, the title has to come in italics. I found a way for the output to come in italics using
f'\033[3m{title}\033[0m'
The problem is that I want the user to be able to copy and paste the reference in their document, however if you try to copy the output on the console, and paste it anywhere, the italic formatting is lost.
This is the part of the code:
reference = lastname + ", " + name[0] + ". " + "(" + year + "). " + f'\033[3m{title}\033[0m' + ". " + place + ": " + editorial + "."

Python Use Dictionary List? What Do I Use

I am making a type of quiz, and want to know how to compare the results to a text file. After answering the questions with prompted input, the function will return a four digit code. I want that four digit code to be compared to "truecode" in a text file I've written out with additional information like this:
villagername,personality,birthday,zodiac,truecode,species
Ankha,snooty,September 22nd,Virgo,A420,Cat
Bangle,peppy,August 27th,Virgo,A330,Tiger
Bianca,peppy,December 13th,Sagittarius,A320,Tiger
Bob,lazy,January 1st,Capricorn,A210,Cat
Bud,jock,August 8th,Leo,A310,Lion
I want this other information to be printed out.
print("Your villager is " + villagername)
print("They are a " + personality + " type villagers and of the " + species + " species.")
print("Their birthday is " + birthday + " and they are a " + zodiac)
print("I hope you enjoyed this quiz!")
I cannot figure out how to extract this information and compare it to what I have. Should I use a list or a dictionary? I'm getting frustrated trying to Google my question and wondering if I went around it all wrong.
How do I compare the four digit code (that will be returned from another function) to "true code" and get everything spit out like above?
import csv
def compare_codes(true_code):
with open(''file.txt) as csvfile:
details_dict = csv.reader(csvfile)
for i in details_dict:
if i['truecode'] == tru_code:
print("Your villager is:",i['villagername'])
print("They are a " + i['personality'] + " type villagers and of the " + i['species'] + " species.")
print("Their birthday is " + i['birthday'] + " and they are a " + i['zodiac'])
print("I hope you enjoyed this quiz!")
break
compare_codes('A420')
Above code reads the text file and compares the input with truecode value in your file and displays the info.
import csv
def get_data(filename):
with open(filename) as f:
reader = csv.DictReader(f, delimiter=',')
data = {row['truecode']: row for row in reader}
return data
def main():
filename = 'results.txt'
data = get_data(filename)
code = input('Enter code: ')
try:
info = data[code]
print("Your villager is " + info['villagername'])
print("They are a " + info['personality'] +
" type villagers and of the " + info['species'] + " species.")
print("Their birthday is " +
info['birthday'] + " and they are a " + info['zodiac'])
print("I hope you enjoyed this quiz!")
except KeyError:
print('Invalid code')
if __name__ == "__main__":
main()
The type of file that you have is actually called a CSV file. If you wanted to, you could open your text file with any spreadsheet program, and your data would show up in the appropriate cells. Use the csv module to read your data.
import csv
def get_quiz_results(truecode):
with open('your-text-file.txt') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
# row is a dictionary of all of the items in that row of your text file.
if row['truecode'] == truecode:
return row
And then to print out the info from your text file
truecode = 'A330'
info = get_quiz_results(truecode)
print("Your villager is " + info["villagername"])
print("They are a " + info["personality"] + " type villagers and of the " + info["species"] + " species.")
print("Their birthday is " + info["birthday"] + " and they are a " + info["zodiac"])
print("I hope you enjoyed this quiz!")
When looping over the file, the csv module will turn each line of the file into a dictionary using the commas as separators. The first line is special, and is used to create the dictionary keys.

Writing Data to an output file in Python

I am very new to scripting (this is my first one) and I'm trying to automate network tasks with python. I have built a script that takes a list of AP names from a text file and puts those ap names into the appropriate place within lines of configuration.
What I would really like is to have the final result saved to a file instead of printed to screen, and nothing I've tried yet has worked. Here's my script that prints to screen
f1=open("filename.txt","r")
Lines=f1.readlines()
for line in Lines:
line = line.strip()
o1="ap name " + (line) + " lan port-id 1 enable"
o2="ap name " + (line) + " lan port-id 2 enable"
o3="ap name " + (line) + " lan port-id 3 enable"
print(o1)
print(o2)
print(o3)
f1.close()
So, this works but then I'm having to copy paste it out of the print. I'd love to have it automatically export to a text file, but none of the things I've tried yet have worked. Thanks for the help!
You just need to open a file for writing and tell print to use that file via the file argument, instead of sys.stdout.
with open("filename.txt", "r") as input, open("newfile", "w") as output:
for line in input:
line = line.strip()
for i in [1,2,3]:
print(f"ap name {line} lan port-id {i} enable", file=output)
The problem maybe with you opening in "w" mode as it erases and rewrites. Try "a" mode.
f1=open("filename.txt","r")
Lines=f1.readlines()
for line in Lines:
line = line.strip()
o1="ap name " + (line) + " lan port-id 1 enable"
o2="ap name " + (line) + " lan port-id 2 enable"
o3="ap name " + (line) + " lan port-id 3 enable"
print(o1)
print(o2)
print(o3)
f2 = open("result.txt","a")
f2.write("o1: %s\n" % o1)
f2.write("o2: %s\n" % o2)
f2.write("o3: %s\n" % o3)
f2.close()
f1.close()

Looping through an json request Alexa skill

I seem to be having an issue with looping through the data that I pulled from a url in my Alexa skill, here is my sample code:
def get_elevator_status():
session_attributes = {}
card_title = "Septa Elevator Status"
reprompt_text = ""
should_end_session = False
response = urllib2.urlopen(API_BASE_URL + "/elevator")
septa_elevator_status = json.load(response)
for elevators in septa_elevator_status['results']:
speech_output = "The following elevators are out of service." "On " + elevators['line'] + " at station " + elevators['station'] + " the " + elevators['elevator'] + " elevator has " + elevators['message']
If I run the code in python shell and print out the results (if there are multiple outages) it prints out all lines. But when I test my Alexa skill and ask for outages it only reports back one result even though there are multiple elevator outages. Am I missing something for this to work? Should this code loop through and say all results found right?
can you post the 'response' json, my guess is that the json is not formed correctly
While looping through the result set everytime you are overwriting speech_output with that particular elevators. Instead, you have to concatenate every result to speech_output.
for elevators in septa_elevator_status['results']:
speech_output = speech_output + " <s> The following elevators are out of service." "On " + elevators['line'] + " at station " + elevators['station'] + " the " + elevators['elevator'] + " elevator has " + elevators['message'] + "</s>"
<s> is the sentence tag, use it only if you are using SSML.

Python: File Writing Adding Unintentional Newlines on Linux Only

I am using Python 2.7.9. I'm working on a program that is supposed to produce the following output in a .csv file per loop:
URL,number
Here's the main loop of the code I'm using:
csvlist = open(listfile,'w')
f = open(list, "r")
def hasQuality(item):
for quality in qualities:
if quality in item:
return True
return False
for line in f:
line = line.split('\n')
line = line[0]
# print line
itemname = urllib.unquote(line).decode('utf8')
# print itemhash
if hasQuality(itemname):
try:
looptime = time.time()
url = baseUrl + line
results = json.loads(urlopen(url).read())
# status = results.status_code
content = results
if 'median_price' in content:
medianstr = str(content['median_price']).replace('$','')
medianstr = medianstr.replace('.','')
median = float(medianstr)
volume = content['volume']
print url+'\n'+itemname
print 'Median: $'+medianstr
print 'Volume: '+str(volume)
if (median > minprice) and (volume > minvol):
csvlist.write(line + ',' + medianstr + '\n')
print '+ADDED TO LIST'
else:
print 'No median price given for '+itemname+'.\nGiving up on item.'
print "Finished loop in " + str(round(time.time() - looptime,3)) + " seconds."
except ValueError:
print "we blacklisted fool?? cause we skippin beats"
else:
print itemname+'is a commodity.\nGiving up on item.'
csvlist.close()
f.close()
print "Finished script in " + str(round(time.time() - runtime, 3)) + " seconds."
It should be generating a list that looks like this:
AWP%20%7C%20Asiimov%20%28Field-Tested%29,3911
M4A1-S%20%7C%20Hyper%20Beast%20%28Field-Tested%29,4202
But it's actually generating a list that looks like this:
AWP%20%7C%20Asiimov%20%28Field-Tested%29
,3911
M4A1-S%20%7C%20Hyper%20Beast%20%28Field-Tested%29
,4202
Whenever it is ran on a Windows machine, I have no issue. Whenever I run it on my EC2 instance, however, it adds that extra newline. Any ideas why? Running commands on the file like
awk 'NR%2{printf $0" ";next;}1' output.csv
do not do anything. I have transferred it to my Windows machine and it still reads the same. However, when I paste the output into Steam's chat client it concatenates it in the way that I want.
Thanks in advance!
This is where the problem occurs
code:
csvlist.write(line + ',' + medianstr + '\n')
This can be cleared is you strip the space
modified code:
csvlist.write(line.strip() + ',' + medianstr + '\n')
Problem:
The problem is due to the fact you are reading raw lines from the input file
Raw_lines contain \n to indicate there is a new line for every line which is not the last and for the last line it just ends with the given character .
for more details:
Just type print(repr(line)) before writing and see the output

Categories