2016-10-26 36 views
0

我正在嘗試構建基於文本的冒險遊戲。還處於發展的早期階段,而且我將許多問題等同於給定的句子與方向和/或動作命令。這是迄今爲止我所擁有的片段。會收到錯誤「列表對象有沒有屬性替換」:將值與已知的關鍵詞後替換列表中的條目(sentence.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") 

,我需要刪除所有未知的話,我想我可以用一組類似的嵌套循環檢查做如果原始句子和修改後的單詞有匹配的話,則刪除它們。在此之後,我需要使列表中的字符串數值成爲整數並將它們相乘。我確實有內置的替代邏輯來糾正句子中的否定,但它完美地起作用。任何幫助,將不勝感激

+4

使用'sentence_parsing.lower()'減少你'travel'三個要素。 – Graipher

+2

也可以代替兩個循環,您可以使用'in'運算符來測試命令是否在列表'travel'中:'in command_parsing:if command.lower()in travel:do_stuff()' – Aaron

回答

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.'] 
0

試試這個:

travel[action] = "1" 

,但我認爲你必須使用字典,或者列表值分配給特定的號碼。例如:

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

P.S您必須應用.replace()到字符串列表,而不是完整的列表。像這樣:travel[0].replace()

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]