-3

So I have this python file that is supposed to count the number of times a color appears in a line. There are 5000 lines in the textfile being called upon and analyzed by this python file. I can't seem for the life of me to figure out how to make it so Python only adds one to the count of a number regardless of how many times a color appears in the line.

For example: in the textfile say there's a line that says "Purple Orange Blue Orange Yellow". It should only count Orange once, even though orange appears twice.

Thanks.

Here's the code. I've put below in the comments something that I thought could work, but I don't know if it would and I'm unsure where I'd even put it.

# Reads slot machine results from file and then analyzes the results, ignoring duplicates.


def main():
    infile_name = input('Please enter the name of the input file: ')
    infile = open(infile_name, 'r')
    color_count = {}

    for line in infile:
        slot_values = line.split()
        for slot_value in slot_values:
            color_count[slot_value] = color_count.get(slot_value, 0) + 1

    infile.close()

    these_keys = list(color_count.keys())
    these_keys.sort()

    for this_key in these_keys:
        print('{0:<10}{1:>7}'.format(
            this_key, color_count.get(this_key)))


main()

# def find_unique_values(value_list):
#  unique_values = ['Purple', 'Orange', 'Blue', 'Yellow', 'Red']

# for value in value_list:
#    if value not in unique_values:
#       unique_values.append(value)

#    return unique_values
  • 2
    If you don't yet know whether your code works, you do not *yet* have a Stack Overflow question. To work with your existing problem, we generally require a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Prune Mar 12 '20 at 22:45
  • Does this answer your question? [Removing duplicates in lists](https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists) – Mark Snyder Mar 12 '20 at 22:45
  • 1
    Also, removing duplicates is a topic covered quite well on line and in other questions. Besides `set`, another way is to test `if color_name in input_line:`; this simply checks whether that color appears anywhere in the line, regardless of how many times it appears. – Prune Mar 12 '20 at 22:46

1 Answers1

1

You can use a set to get rid of duplicates in your slot_values.

slot_values = set(line.split())
Mark Snyder
  • 1,635
  • 3
  • 12