'How to print every variable from biggest to smallest in python
I'm working on a zif's law project in python. I wrote this code:
import os
my_file = open("words.txt", "r")
content = my_file.read()
w = content.split()
my_file.close()
def split(a):
return[char for char in a]
x = 0
for i in range(len(w)):
w[x] = w[x].lower()
s = split(w[x])
y = 0
for i in range(len(s)):
if s[y] == "." or s[y] == s[y] == "," or s[y] == "'" or s[y] == "0" or s[y] == "1" or s[y] == "2" or s[y] == "3" or s[y] == "4" or s[y] == "5" or s[y] == "6" or s[y] == "7" or s[y] == "8" or s[y] == "9":
s[y] = ''
y += 1
s = "".join(s)
w[x] = s
x += 1
o = open("wzl.py", "w")
x = 0
p = 0
for i in range(len(w)):
if x == (len(w) - 1):
break
y = 0
o.write(f"{w[x]}1 = 1")
o.write("\n")
for i in range(len(w) - 1):
y += 1
if w[x] == w[y]:
o.write(f"{w[x]}1 += 1 ")
o.write("\n")
del w[y]
y -= 1
if y == (len(w) - 1):
o.write(f"print('{w[x]} = ', {w[x]}1)")
o.write("\n")
del w[x]
x -= 1
print(w)
x += 1
o.close()
os.system("python wzl.py")
It opens the other file and writes this:
sitting1 = 1
print('sitting = ', sitting1)
in1 = 1
in1 += 1
print('in = ', in1)
the1 = 1
the1 += 1
print('the = ', the1)
sun1 = 1
print('sun = ', sun1)
away1 = 1
print('away = ', away1)
from1 = 1
print('from = ', from1)
everyone1 = 1
print('everyone = ', everyone1)
who1 = 1
print('who = ', who1)
had1 = 1
print('had = ', had1)
done1 = 1
print('done = ', done1)
him1 = 1
print('him = ', him1)
harm1 = 1
print('harm = ', harm1)
Now, all I need is for the code to go through every variable and print the first 10 from biggest to smallest, how do I do that? I think i can do it with class but i don't know how to use it.
Also if you find some way I can improve my code, please note.
Input example: 'Sitting in the sun, away from everyone who had done him harm in the past.'
Output example:
the: 6
he: 5
of: 2
she: 1
Solution 1:[1]
Actually you can use built-in collections module to do this work for you. Why reinvent the wheel when there is a builtin implementation
from collections import Counter as Co
listofwords = 'Hi Hi a a a for be a hi hi hlo hlo'
print(Co(listofwords.split()))
#Counter({'a': 4, 'Hi': 2, 'hi': 2, 'hlo': 2, 'for': 1, 'be': 1})
# if you want to find the 2 most common words
print(a.most_common(2))
#[('a', 4), ('Hi', 2)]
here is an article if you want to read about it
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | joel n |
