pythonoutputtxt

Python output of lines with an entry threshold greater than 1


Python output of lines with occurrence value > 1

Good afternoon, tell me how to display occurrences that have occurred more than once.

The txt file contains the following lines: 1 1 2 3

text = open("dan1.txt").read()
unique = set(text.split())

for word in unique:
    print(f'{word}: {text.count(word)}')

It turns out only to display each line and its value. I don’t understand how to output a string with a value > 1


Solution

  • You could utilise a Counter from the collections module as follows:

    from collections import Counter
    
    with open("dan1.txt") as fd:
        words = fd.read().split()
        counter = Counter(words)
        for k, v in counter.items():
            if v > 1:
                print(k)