Question

In: Computer Science

How to print output vertically in the code attached below: import operator with open ('The Boy...

How to print output vertically in the code attached below:

import operator

with open ('The Boy .txt',encoding='utf8') as my_file:
 contents=my_file.read()

l = contents.strip()
words = l.split()


newdict = dict()

for i in words:
  if i in newdict:
   newdict[i] = newdict[i] + 1
  else:
   newdict[i] = 1

newly = dict()
sorted_Dict = sorted(newdict.items(), key=operator.itemgetter(1), reverse=True)
for n in sorted_Dict:
    newly[n[0]] = n[1]
print(newly)

with open('freqs.txt','w', encoding='utf8') as final:
    final.write(str(newly))







Solutions

Expert Solution

CODE:

file.txt :

OUTPUT:

Note : ls command is used to list the files in the current directory.

freqs.txt :

RAW CODE:

import operator
with open ('file.txt',encoding='utf8') as my_file:
    contents=my_file.read()

l = contents.strip()
words = l.split()

newdict = dict()

for i in words:
  if i in newdict:
   newdict[i] = newdict[i] + 1
  else:
   newdict[i] = 1

sorted_Dict = sorted(newdict.items(), key=operator.itemgetter(1), reverse=True) # sorting dictionary
with open('freqs.txt','w', encoding='utf8') as final: # opening file
    for n in sorted_Dict: # iterate each pair in sorted_Dict
        print(str(n[0]) + "\t" + str(n[1])) # printing each pair vertically separated by tab space into console
        final.write(str(n[0] + "\t" + str(n[1])) + "\n") # writing each pair vertically separated by tab space into file

NOTE:
If You have any doubts feel free to comment in comment section.
DO VOTE(LIKE).


Related Solutions

fix this code in python and show me the output. do not change the code import...
fix this code in python and show me the output. do not change the code import random #variables and constants MAX_ROLLS = 5 MAX_DICE_VAL = 6 #declare a list of roll types ROLLS_TYPES = [ "Junk" , "Pair" , "3 of a kind" , "5 of a kind" ] #set this to the value MAX_ROLLS pdice = [0,0,0,0,0] cdice = [0,0,0,0,0] #set this to the value MAX_DICE_VAL pdice = [0,0,0,0,0,0] cdice = [0,0,0,0,0,0] #INPUT - get the dice rolls i...
What does each line of this python code do? import datetime import getpass print("\n\nFinished execution at...
What does each line of this python code do? import datetime import getpass print("\n\nFinished execution at ", datetime.datetime.now()) print(getpass.getuser())
this is my code in python I am trying to open a file and then print...
this is my code in python I am trying to open a file and then print the contents on my console but when i run it nothing prints in the console def file_to_dictionary(rosterFile): myDictionary={}    with open(rosterFile,'r') as f: for line in f: myDictionary.append(line.strip()) print(myDictionary)             return myDictionary    file_to_dictionary((f"../data/Roster.txt"))      
Implement a Factory Design Pattern for the code below: MAIN: import java.util.ArrayList; import java.util.List; import java.util.Random;...
Implement a Factory Design Pattern for the code below: MAIN: import java.util.ArrayList; import java.util.List; import java.util.Random; public class Main { public static void main(String[] args) { Character char1 = new Orc("Grumlin"); Character char2 = new Elf("Therae"); int damageDealt = char1.attackEnemy(); System.out.println(char1.name + " has attacked an enemy " + "and dealt " + damageDealt + " damage"); char1.hasCastSpellSkill = true; damageDealt = char1.attackEnemy(); System.out.println(char1.name + " has attacked an enemy " + "and dealt " + damageDealt + " damage");...
import math print("RSA ENCRYPTION/DECRYPTION") print("*****************************************************") #Input Prime Numbers print("PLEASE ENTER THE 'p' AND 'q' VALUES BELOW:")...
import math print("RSA ENCRYPTION/DECRYPTION") print("*****************************************************") #Input Prime Numbers print("PLEASE ENTER THE 'p' AND 'q' VALUES BELOW:") p = int(input("Enter a prime number for p: ")) q = int(input("Enter a prime number for q: ")) print("*****************************************************") #Check if Input's are Prime '''THIS FUNCTION AND THE CODE IMMEDIATELY BELOW THE FUNCTION CHECKS WHETHER THE INPUTS ARE PRIME OR NOT.''' def prime_check(a): if(a==2): return True elif((a<2) or ((a%2)==0)): return False elif(a>2): for i in range(2,a): if not(a%i): return false return True check_p =...
Fill in the format strings so that the print() statements below display the indicated values vertically aligned
Use pythonFill in the format strings so that the print() statements below display the indicated values vertically aligned as Class | Exam Type | Grade ---------- | ---------- | ------------- ECC102 | Midterm | 78.12 ECC104 | Final | 82.45 ECC108 | Makeup | 98.00 ECC200 | Resit | 100.00 Note that the Class column is aligned LEFT, Exam Type column is aligned MIDDLE, and Grade column is also aligned LEFT. Note also that you need to use the vertical...
C++ program. Please explain how the code resulted in the output. The code and output is...
C++ program. Please explain how the code resulted in the output. The code and output is listed below. Code: #include <iostream> #include <string> using namespace std; int f(int& a, int b) {    int tmp = a;    a = b;    if (tmp == 0) { cout << tmp << ' ' << a << ' ' << b << endl; }    b = tmp;    return b;    return a; } int main() {    int a...
Your code must print all the steps in the output as an Eg> When you run...
Your code must print all the steps in the output as an Eg> When you run your Merge sort code the sequence of output should be: 1) Enter input sequence 2) Show n/2 division of the input sequence 3) keep showing n/2 division of your sequence until you get one attribute 4) Sort first two numbers 5) Make a stack of 4 by merging 2 * 2 and sort them 6) keep showing merging and sorting until you show the...
Python I am creating a class in python. Here is my code below: import csv import...
Python I am creating a class in python. Here is my code below: import csv import json population = list() with open('PopChange.csv', 'r') as p: reader = csv.reader(p) next(reader) for line in reader: population.append(obj.POP(line)) population.append(obj.POP(line)) class POP: """ Extract the data """ def __init__(self, line): self.data = line # get elements self.id = self.data[0].strip() self.geography = self.data[1].strip() self.targetGeoId = self.data[2].strip() self.targetGeoId2 = self.data[3].strip() self.popApr1 = self.data[4].strip() self.popJul1 = self.data[5].strip() self.changePop = self.data[6].strip() The problem is, I get an error saying:  ...
Question #1 Please specify he output of the following code (2.4) # import the pandas library...
Question #1 Please specify he output of the following code (2.4) # import the pandas library and aliasing as pd import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(8, 4), index = ['a','b','c','d','e','f','g','h'], columns = ['A', 'B', 'C', 'D']) # for getting values with a boolean array print df.loc['a']>0 Question #2 Please specify the output of the following code (2.2) import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', 'h'],columns=['one', 'two',...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT