I would like to count a list of words in a.txt file using python

Asked

Viewed 81 times

-2

I have this code that counts the number of occurrences of a string in a.txt file and returns it to me. But I would like to use a list of items or an array. And that he would return to me the occurrence of each of these items. The current code is this:

 word = "12510537019"

 def counting(Text_File, Word):

    Data = open(Text_File, "r").read()

    count = Data.count(Word)

    print(Word, ":", count)

counting("arquivo.txt", word)

But I’d like to start with something like this:

word = [
    "12510537019",
    "21185356784",
    "22097245854",
    "16427169000",
    "12464413424",
    "13506742816",
    "11990657689"]

How to do?

  • What you want is to count the frequency of each word in a text from a list of words? That is, the amount of each word in the list in the text?

1 answer

0


You can try using list comprehension:

wordList = [
    "12510537019",
    "21185356784",
    "22097245854",
    "16427169000",
    "12464413424",
    "13506742816",
    "11990657689"]

ocorrencias = [counting("arquivo.txt", word) for word in wordList]

This will generate a new list of occurrences of each word in the file:

print(ocorrencias)
#[3,6,2,1,9,8,7]

Keep in mind that this is the fastest way to do it, but it is not the most efficient. What it does is re-call the function counting for each word in the list, making the file open and closed multiple times. For an example of learning or something small I believe to have no problems.

  • Okay, so what would be the most efficient way?

  • I asked above about what would be the most efficient way because I want to learn it! If you can teach me I will be grateful!

  • @83HappyDog. Sorry, I hadn’t read it. When I wrote the answer I was referring to opening the file only once, telling everything that is necessary, and returning. For this you would have to modify the internal function a little, instead of calling it several times. I don’t think she should print anything inside her either, just on the main show. The same list comprehension structure can be used within the function, to use the Count function for all list elements.

  • Okay. But how could I do that in practice? Could I use map() or in which case it shall not apply?

  • We share the same idea about opening the file only once and telling you everything that is needed. But it is at this point that I am losing myself. That’s why I asked above, about how to promote these changes in practice?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.