Home > front end >  How to change ints in lists?
How to change ints in lists?

Time:05-22

I wrote a function to calculate the number of words of a particular length and write it on the console.

def count():
read_data = file.read()
list_count = list(map(lambda word: len(word), read_data.split()))
list_count.sort()
counted_words = collections.Counter(list_count)
for key, value in counted_words.items():
    print(f"there are: {value} words of length: [{key}].")

I don't know how I can turn it into a list to draw a graph using matplotlib.pyplot.

CodePudding user response:

you define an empty list , a boucle for and each iteration you use append to add the len of the word. What values do you want on X and Y it's not clear

Edit :

You can use the following code

plt.plot(counted_words.keys(), counted_words.values(),label="your label")
plt.legend(loc="upper left")
plt.title("Your title")
plt.xlabel("Name for the X axes")
plt.ylabel("Name for the Y axes")

CodePudding user response:

Maybe this will help. Write a function that takes a filename as its only argument and which returns a Counter. You can then iterate over the Counter and plot according to the values found.

from collections import Counter

def count(filename):
    counter = Counter()
    with open(filename) as infile:
        for line in map(str.strip, infile):
            for word in line.split():
                counter[len(word)]  = 1
    return counter

for k, v in count('YourFilenameGoesHere').items():
    print(f'There are {v} words of length {k}')
  • Related