Find the required strings in a text file, then count them and compare them

Asked 2 years ago, Updated 2 years ago, 17 views

I'd like to find the necessary strings in the txt file and extract them to find out the total number and compare them.

I'll skip the code I've created and show you!

f = open
file = f.read()
file_s = file.split()

a = [String Required 1]
b = [Required strings 2]

p_a = 0
p_b = 0

For c in file_s: # (I don't think I need the variable c, so I'm thinking of using while file_s!= 0.)
    if ???.count()???>= 1 :
        p_a += 1
    elif ???.count()???>= 1:
        p_b += 1
    if p_a > p_b:
        print("a")
        break
    elif p_a == p_b:
        print ("=")
        break
    else:
        print("b")
        break

The problem here is if and elif with a question mark just below the for statement. (Of course, there may be problems with other parts, but in my view, I don't know anything at the moment.)

I know I have to use the count function, but I don't know how to use it.

Among the strings I need within txt. If there is a string in list a, I want to add 1 to p_a, and if there is a string in list b, I want to add 1 to p_b.

However, since there are several strings required, I want to know the number of strings, and compare the number of strings to output a value with a large number. I don't know if I explained it well.

python

2022-09-22 19:16

1 Answers

You can save the count of every word in the document in advance, find the word you want to find individually in every word, and add the count.

from collections import Counter

a = ('dhclient', '5828', 'bioset')
b = ('vmstat', 'bioset', '0:00.00')

f = open('...')

wordcount = Counter(f.read().split()) # Count words from file. Sorted in descending order of size

p_a = sum(wordcount[word] for word in a) # Add the number of words present in a
p_b = sum(wordcount[word] for word in b) # Add the number of words present in b

print(p_a, p_b)


2022-09-22 19:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.