简体   繁体   中英

Replace a element (word) in a list with an element (word) from a different list

I keep getting this error message for my code and I don't understand why.

error:

Please provide a message: darn it boy

Traceback (most recent call last):
  File "bleep.py", line 40, in <module>
    main()
  File "bleep.py", line 26, in main
    user_list_lower[item] = beep[0]
TypeError: list indices must be integers or slices, not str

code:

#x.strip() for x in 
import sys

def main():

    if len(sys.argv) < 2:
        sys.exit("Must enter text. status code 1")

    with open(sys.argv[1], 'r') as f:
        content = f.read()

    content_list = content.split("\n") 

    user_input = input("Please provide a message: ")

    user_list = user_input.split()

    while '' in content_list:
        content_list.remove('')

    user_list_lower = [x.lower() for x in user_list] 

    for item in user_list_lower:
        if item in content_list:
            beep = [len(item) * '*']
            user_list_lower[item] = beep[0]
            print (user_list_lower)
            print(beep)
        else:
            break


    print(content_list)
    print(user_list_lower)

    return content


if __name__== "__main__":
    main()

As user input I use: Darn it boy. It does not change darn it to **** as it should.

In the command line argument I give a text file that contains few swear word, of which 'darn' is one. My code works but it just doesn't change the word darn to '****'

In the loop, you are trying to use item to index user_list_lower , but item is the list element, not its index. Try using enumerate :

for idx, item in enumerate(user_list_lower):
    if item in content_list:
        beep = [len(item) * '*']
        user_list_lower[idx] = beep[0]
        print (user_list_lower)
        print(beep)
    else:
        break

In addition to that, consider making content_list into a set , which will make checking if item in content_list much faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM