Andrew Burton Andrew Burton - 1 year ago 69
Python Question

Replacing an entry in a list (sentence.replace())

I'm trying to build a text based adventure game. still in early stages of development, and I'm having a lot of problems with equating a given sentence to directional and or action commands. here is a snippet of what I have so far. will get the error "list object has no attribute replace":

sentence_parsing = input().split(" ")

travel = ["Move", "move", "MOVE", "Go", "go", "GO", "Travel", "travel", "TRAVEL"]
command_length = len(sentence_parsing)
for command in range(command_length):
for action in range(9):
if travel[action] == sentence_parsing[command]:
sentence_parsing = sentence_parsing.replace(travel[action], "1")

after applying values to known key words, I need to remove all unknown words, which I think I can do with a similar set of nested loops checking if the original sentence and the modified have matching words then remove if they do. after that I need to make the string number values in the list become integers and multiply them together. I do have alternative logic built in to correct negation in sentences, but it works perfectly. Any help would be appreciated

Answer Source

Instead of iterating through travel, you might want to iterate through the words in sentence_parsing instead.

# Make sure that your parser is not case-sensitive by transforming 
# all words to lower-case:
sentence_parsing = [x.lower() for x in input().split(" ")]

# Create a dictionary with your command codes as keys, and lists of 
# recognized command strings as values. Here, the dictionary contains
# not only ``travel'' commands, but also ``eat'' commands:
commands = {
    "1": ["move", "go", "travel"],
    "2": ["consume", "gobble", "eat"]}

# Iterate through the words in sentence_parsing. 
# ``i'' contains the index in the list, ``word'' contains the actual word:
for i, word in enumerate(sentence_parsing):
    # for each word, go through the keys of the command dictionary:
    for code in commands:
         # check if the word is contained in the list of commands 
         # with this code: 
         if word in commands[code]:
             # if so, replace the word by the command code:
             sentence_parsing[i] = code

With the input string

Go north. Eat fruit. Travel east. Consume goblin.

the list sentence_parsing looks like this after execution of the code:

['1', 'north.', '2', 'fruit.', '1', 'east.', '2', 'goblin.']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download