PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 7, 2022

[FIXED] How to not make text file whos lines I split not have duplicate output using a set

 November 07, 2022     python, python-3.x, set, text-files     No comments   

Issue

Hello so I have a file that I have split into containers and are pulling from them. I confirmed that all of them are the same and pulling [3] will get me a code and [7] will get me a result. But [7] has lines that repeat and I only want one instance of [7] to show. I'm trying to use sets but I cant find a way to use it. I've looked up sets and understand a bit, but I can't figure out how to use it. Thank you for reading.

f = open(textfile.txt", "r")

error = f.readlines()

for l in error:
    s = l.split()
    if "70" in s[3]:
        print("Error:", s[3], "Color:", s[7])

f.close()

Right now it will show up as:

Error: 701 Color: Purple
Error: 701 Color: Purple
Error: 702 Color: Pink
Error: 702 Color: Pink
Error: 702 Color: Pink
Error: 705 Color: Black
Error: 705 Color: Black
Error: 705 Color: Black
Error: 705 Color: Black

But I want it to show up as:

Error: 701 Color: Purple
Error: 702 Color: Pink
Error: 705 Color: Black

Solution

Use set is a wise choice, it won't contain duplicated elements.

errorMessages = set()

f = open("textfile.txt", "r")

error = f.readlines()

for l in error:
    s = l.split()
    if "70" in s[3]:
        errorMessages.add(f"Error: {s[3]} Color: {s[7]}")

f.close()

for msg in errorMessages:
    print(msg)


Answered By - Shimizu Hino
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing