替换列表中的条目(sentence.replace())

时间:2016-10-26 17:00:40

标签: python

我正在尝试构建基于文本的冒险游戏。仍然处于开发的早期阶段,我在将给定句子等同于方向和/或动作命令方面遇到了很多问题。这是我到目前为止的一个片段。将得到错误"列表对象没有属性替换":

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")

在将值应用于已知关键词后,我需要删除所有未知单词,我认为我可以使用类似的嵌套循环集来检查原始句子和修改后的单词是否匹配,然后删除它们。之后,我需要使列表中的字符串数值成为整数并将它们相乘。我确实有内置的替代逻辑来纠正句子中的否定,但它完美地运作。任何帮助将不胜感激

3 个答案:

答案 0 :(得分:3)

input().split()

给你一个字符串列表。您可以使用for循环一次检查一个。

for command in sentence_parsing:
    if command in travel:
        #do something
    else:
        #do a different thing

如果您只想保留旅行中识别的单词,您可以:

sentence_parsing = [command for command in sentence_parsing if command in travel]

答案 1 :(得分:2)

您可能希望迭代travel中的字词,而不是遍历sentence_parsing

# 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

使用输入字符串

  

向北走。吃水果。向东旅行。消耗地精。

执行代码后列表sentence_parsing如下所示:

['1', 'north.', '2', 'fruit.', '1', 'east.', '2', 'goblin.']

答案 2 :(得分:0)

试试这个:

travel[action] = "1"

但我认为你必须使用dict,或者为列表中的特定数字赋值。例如:

>>>list = [0, 0]
>>>list
[0, 0]
>>>list[1] = "1"
>>>list
[0, '1']

P.S您必须将.replace()应用于列表中的字符串,而不是完整列表。像这样:travel[0].replace()