我正试着建立一个基于文本的冒险游戏。我仍然处于开发的早期阶段,在将给定的句子等同于定向和或动作命令方面,我遇到了很多问题。这是我到目前为止所得到的一些片段。将得到错误“列表对象没有属性替换”:
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")在将值应用到已知关键字之后,我需要删除所有未知单词,我认为这可以使用类似的嵌套循环来完成,检查原始句子和修改后的单词是否有匹配的单词,如果有,则删除。在此之后,我需要使列表中的字符串数值变为整数,并将它们相乘。我确实有可选择的逻辑来纠正句子中的否定,但它工作得很好。如能提供任何帮助,将不胜感激。
发布于 2016-10-26 17:12:09
与其在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.']发布于 2016-10-26 17:06:11
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]发布于 2016-10-26 17:05:44
试试这个:
travel[action] = "1"但是我认为你必须使用dict,或者给列表中的特定数字赋值。例如:
>>>list = [0, 0]
>>>list
[0, 0]
>>>list[1] = "1"
>>>list
[0, '1']您必须将.replace()应用于列表中的字符串,而不是完整的列表。像这样:travel[0].replace()
https://stackoverflow.com/questions/40268150
复制相似问题