首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >替换列表中的条目(sentence.replace())

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

Stack Overflow用户
提问于 2016-10-26 17:00:40
回答 3查看 150关注 0票数 0

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

代码语言:javascript
复制
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")

在将值应用到已知关键字之后,我需要删除所有未知单词,我认为这可以使用类似的嵌套循环来完成,检查原始句子和修改后的单词是否有匹配的单词,如果有,则删除。在此之后,我需要使列表中的字符串数值变为整数,并将它们相乘。我确实有可选择的逻辑来纠正句子中的否定,但它工作得很好。如能提供任何帮助,将不胜感激。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-10-26 17:12:09

与其在travel中迭代,不如使用sentence_parsing中的单词进行迭代。

代码语言:javascript
复制
# 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如下所示:

代码语言:javascript
复制
['1', 'north.', '2', 'fruit.', '1', 'east.', '2', 'goblin.']
票数 2
EN

Stack Overflow用户

发布于 2016-10-26 17:06:11

代码语言:javascript
复制
input().split()

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

代码语言:javascript
复制
for command in sentence_parsing:
    if command in travel:
        #do something
    else:
        #do a different thing

如果你只想保留你在旅行中认出的单词,你可以这样做:

代码语言:javascript
复制
sentence_parsing = [command for command in sentence_parsing if command in travel]
票数 3
EN

Stack Overflow用户

发布于 2016-10-26 17:05:44

试试这个:

代码语言:javascript
复制
travel[action] = "1"

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

代码语言:javascript
复制
>>>list = [0, 0]
>>>list
[0, 0]
>>>list[1] = "1"
>>>list
[0, '1']

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40268150

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档