Home > OS >  Censoring code using tuples and lists [python]
Censoring code using tuples and lists [python]

Time:10-11

I need to write code which, when provided with a tuple containing an IP address of a sender and a text message they sent (e.g. ("1.2.3.4", "I hate mondays")), monitors for the presence of keywords within their message and replaces the keywords with the same number of * as the length of the censored word. In the event that words are censored the code should print a tuple of the IP address of the offender and the censored string. If no offending words are found then the code should print "No banned words found."

This is what I have written so far, but I need to make the program compare and replace banned words with ****

banned_words = ['darwkeb','fakenews','deepweb','cyber','nextgen','internet-of-things',
                'iot']
ip = input("Enter ip address: ")
msg = str(input("Enter msg: ")).lower()
data = ([ip],[msg])
split_msg = msg.split()

for i in split_msg:
    if i in banned_words:
        i_index = split_msg.index(i) #to get the mag index
        split_msg.remove(i) #removing the msg
        split_msg.insert(i_index, "****") #insert **** to that index

print(split_msg)
' '.join(split_msg)
# elif condition to print" no banned words" causes indentation error
    elif i not in banned_words:
        print("no banned words.")

CodePudding user response:

You can use for loop -

banned_words = ['darweb','fakenews','deepweb','cyber','nextgen','internet-of-things',
                'iot']
ip = input("Enter ip address: ")
msg = str(input("Enter msg: "))
data = ([ip],[msg])
print(data)
split_msg = msg.split()

for i in split_msg:
    if i in banned_words:
        i_index = split_msg.index(i) #to get the mag index
        split_msg.remove(i) #removing the msg
        split_msg.insert(i_index, "****") #insert **** to that index

print(split_msg)

terminal logs:

Enter ip address: ip    
Enter msg: hello how are darweb works perfectly nextgen
(['ip'], ['hello how are darweb works perfectly nextgen'])
['hello', 'how', 'are', '****', 'works', 'perfectly', '****']

error solved:

for i in split_msg:
    if i in banned_words:
        i_index = split_msg.index(i) #to get the mag index
        split_msg.remove(i) #removing the msg
        split_msg.insert(i_index, "****") #insert **** to that index

        print(split_msg)
        ' '.join(split_msg)
# elif condition to print" no banned words" causes indentation error
    elif i not in banned_words:
        print("no banned words.")
  • Related