Python 2 Sorting from a text file [duplicate] - python

This question already has answers here:
I have wrong results with sorting function at python
(2 answers)
Closed 2 years ago.
Im trying to write a code where user puts in their score (a number), and then they put in their name. both the score and name gets stored in a text file (alongside with '\n', so that every new couple gets stored on the new line).
hscores = open("highscores.txt", "a")
hscores.write(str(score))
hscores.write(" ")
hscores.write(nickname)
hscores.write("\n")
hscores.close()
then, I open the text file, take every input in there, sort it by highest to lowest and output it:
hscores22 = open("highscores.txt", "r")
listings2 = hscores22.readlines()
sorting2 = sorted(listings2, reverse=True)
print "| 1 | " + sorting2[0]
print "| 2 | " + sorting2[1]
print "| 3 | " + sorting2[2]
print "| 4 | " + sorting2[3]
print "| 5 | " + sorting2[4]
print "| 6 | " + sorting2[5]
print "| 7 | " + sorting2[6]
print "| 8 | " + sorting2[7]
print "| 9 | " + sorting2[8]
print "| 10 | " + sorting2[9]
The problem is that python thinks that number that starts with the biggest number, is bigger, for example: 90>1000, 50>100 (I suppose thats because i have to convert all the numbers to strings before storing them in the text file). is there any way i could fix this?
thanks in advance.

Since you're sorting strings, Python is comparing them lexicographically - so '2' is bigger than '1'. You need to extract the numeric part of your string, convert it to a number and use this number for sorting key:
sorting2 = sorted(listings2, reverse=True, key=lambda x: int(x.split()[0]))
BTW, next 10 lines really ask to be replaced by a for loop…

Related

How to put string inside string (variable) in Python?

I tried to run some python code, but it says "[pyflakes] unexpected EOF while parsing"
My code is:
if "debug " in code:
print(" |" + x + "|" + y + "| ")
Edit: Also do NOT say duplicate I tried the answer of the other question and it didn't work. I use Python 3.8.2
Try using an f-string.
if "debug " in code:
print(f" | {x} | {y} | ")

Worksheet Creation

I am trying to make a math worksheet for grade schoolers. I wanted to make it as a np.random.randint function to generate some 2-digit, 3-digit and 4-digit numbers then process the numbers to form a worksheet in the manner that a grade schooler is used to.
I having trouble joining the number generated to look like this 1
With my current code I got to this
q1=q2=[]
q1= [two_digit[0],two_digit[1]]
q2=[two_digit[2],two_digit[3]]
addition="+".join(map(str,q2))
print(addition)
this gives an output like this
55+50
is there a better way to manipulate int to become string then go into a format that can be printed out easily?
You can use new lines and the unicode upperscore.
questions = [q1, q2]
nr_of_digits = 2
for q in questions:
q = list(map(str,q))
print(" " + q[0] + "\n" + "+" + q[1] + "\n" + u'\u0305' * (nr_of_digits + 1) + "\n")

Set all lines with the same quantity of spaces - even those lines with emojies on them

I'm self-learning Python and I'm doing a program using Python and Pytube for retrieve information for a YouTube video.
The information of the YouTube video to get is:
Title
Author
Description
I want to set this information in the following structure:
Simplified example - info extracted from YouTube video_id: kqtD5dpn9C8
┌──────────────────────────────────────────────────────────────┐
| |
| 📕 Get my FREE Python cheat sheet: http://bit_ly/2Gp80s6 |
| |
| Courses: https://codewithmosh.com |
| Twitter: https://twitter.com/moshhamedani |
| Facebook: https://www.facebook.com/programmingwithmosh/ |
| Blog: http://programmingwithmosh.com |
| |
| #Python, #MachineLearning, #WebDevelopment |
| |
| 📔 Python Exercises for Beginners: https://goo_gl/1XnQB1 |
| |
| ⭐ My Favorite Python Books |
| - Python Crash Course: https://amzn.to/2GqMdjG |
| |
| TABLE OF CONTENT |
| |
| 0:00:00 Introduction |
| 0:00:30 What You Can Do With Python |
| 0:57:43 Tuples |
| |
└──────────────────────────────────────────────────────────────┘
The problem I'm facing currently is as follows:
When formatting the "description" info, there are some lines that has emojis on them; the code I share below sets all lines the description has with equal size; however, due to the emoji, an additional "space" is shown and the format is visually broken.
Code:
# Line # 1 - without emojis:
item = "#Python, #MachineLearning, #WebDevelopment"
emptyLine = "| |"
# Difference between length of the line and the empty line.
# It is used for concatenate to the line in construction "spaces" and "|" char |.
diffChars = len(emptyLine)-len(item)
item = item + (" "*(diffChars-4)) + " |"
print("| " + item)
# ----------------------------
Result:
| #Python, #MachineLearning, #WebDevelopment |
# Line # 2 - with emoji:
item = "📔 Python Exercises for Beginners: https://goo_gl/1XnQB1"
emptyLine = "| |"
# Difference between length of the line and the empty line.
# It is used for concatenate to the line in construction "spaces" and "|" char |.
diffChars = len(emptyLine)-len(item)
if (diffChars % 2 == 0):
diffChars = diffChars - 1
#print("Qty characters difference (2): " + str(diffChars))
item = item + (" "*(diffChars-4)) + " |"
print("| " + item)
# ----------------------------
Result:
| 📔 Python Exercises for Beginners: https://goo_gl/1XnQB1 |
# Line # 3 - without emojis:
item = "0:25:59 Operator Precedence "
emptyLine = "| |"
# Difference between length of the line and the empty line.
# It is used for concatenate to the line in construction "spaces" and "|" char |.
diffChars = len(emptyLine)-len(item)
if (diffChars % 2 == 0):
diffChars = diffChars - 1
#print("Qty characters difference (2): " + str(diffChars))
item = item + (" "*(diffChars-4)) + " |"
print("| " + item)
Result:
| 0:25:59 Operator Precedence |
Results of the previous lines:
| #Python, #MachineLearning, #WebDevelopment |
| 📔 Python Exercises for Beginners: https://goo_gl/1XnQB1 | # <= line with diff. in size.
| 0:25:59 Operator Precedence |
As you can see in the results above, the line with the "📔" emoji shows at the end of the line a slight difference - it has an additional "space" - breaking the straight vertical line.
Is there any way to set all lines with the same quantity of spaces - even those lines with emojies on them?
PS: I'm using Google Colab (link to my book with the code so far - n.b. is in spanish) and w3schools.com and in both enviroments I have the same results. You can copy and paste the previous code in Google Colab or in the "try-it" feature of w3schools.com.

Python - newline if variable is in print function, need fix [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 1 year ago.
I have one problem with print in Python, I am starting to learn Python, but when I want to print variables in print function, it looks like that after one variable it adds newline to the outcome:
print(game_name + " | " + rating)
I am making a game database with my own ratings on the games but if it prints the game and the rating there is like one empty line belpw the game_name and rating is written, how can I delete that empty newline? I am very new to this, so please don't be mean...
Welcome to Stack Overflow! The most likely culprit is that there is a newline at the end of the game_name variable. The easy fix for this is to strip it off like this:
print(game_name.strip() + " | " + rating)
Say we had two variables like this.
game_name = 'hello\n'
rating = 'there'
game_name has the newline. To get rid of that use strip().
print(game_name.strip() + " | " + rating)
output
hello | there
If you want to remove the line break after printing, you can define the optional end parameter to the print statement.
print('Hello World', end='') # No new line
If your variable has a new line added to it, and you want to remove it, use the .strip() method on the variable.
print('Hello World\n'.strip()) # No empty line
For your code, you could run it:
print(game_name + " | " + rating, end='')
Or
print(game_name + " | " + rating.strip())
If the error is that a new line is printed after game_name, you'll want to call the strip method on that instead.
print(game_name.strip() + " | " + rating)
rating or game_name most likely have a new line after the specified string.
You can fix it by doing this:
game_name = game_name.strip('\n')
rating = rating.strip('\n')
print(game_name + " | " + rating)

Python, read and write file is cutting final output file to limited number of lines?

So I wrote a small script that will convert my g-code file commands by replacing "G01" to "G1" it is all working perfectly but these files are very big they can end up with more then 10 or 20k lines of code!
My problem is that file with all code converted ends up with 4715 lines but original file has 4817 lines. Funny thing is the for loop is going through all lines but only first 4715 are written(I checked that by simple a = a + 1 every time something is written to a file)!
Here is the code it is very simple!
import string
a = 0
b = 0
s = open("test.gcode","r+")
replaced = open("test_replaced.gcode","a")
for line in s.readlines():
if "G01" in line:
replaced.write(line.replace("G01", "G1" ))
print ("G01 ==> G1")
a = a + 1
elif "G00" in line:
replaced.write(line.replace("G00", "G0" ))
print ("G00 ==> G0")
a = a + 1
else:
replaced.write(line.replace("******", "**" ))
print ("***")
a = a + 1
b = b + 1
#replaced.write(line.replace("G01", "G1" ))
#replaced.write(line.replace("G00", "G0" ))
print ("Done! - " + str(a) + " number of operations done!")
print ("Loopcount: " + str(b))
s.close()
As pointed out in a comment to your question, you should probably replace your open() statements with with statements. So, your code would become.
...
with open("test.gcode","r+") as s:
with open("test_replaced.gcode","a") as replaced:
...
print ("Done! - " + str(a) + " number of operations done!")
print ("Loopcount: " + str(b))
Please note that there is no longer a close() at the end of the script because the context manager (with) closes the file already.
All you code dealing with the files needs to be within the with blocks.
You can find more information about context managers here.

Categories

Resources