0

我有一个列表,其中包含一个名为words. 我有一个random_sentence可以使用任何句子调用的函数。我想在随机句子中搜索列表中[0]每个列表中的任何单词,然后用该列表中的相应单词切换它。希望这是有道理的。

words = [["I", "you"], ["i", "you"], ["we", "you"], ["my", "your"], ["our", "your"]]

def random_sentence(sentence):
   list = sentence.split()
   string = sentence
   for y in list:
      for i in words:
         for u in i:
            if y == u:
              mylist = i[1]
              string = string.replace(y, mylist)
   return string

所以random_sentence("I have a my pet dog") 应该返回“你有你的宠物狗”。我的功能有时有效,但有时无效。说random_sentence("I went and we") 产生“你和你”没有意义。

如何修复我的功能以产生正确的结果?

4

4 回答 4

1

首先,您粘贴的代码甚至无法运行。您的函数定义中有一个空格而不是下划线,并且您永远不会返回任何内容。

但是,在修复它之后,您的代码完全按照您的描述进行。

要找出原因,请尝试添加prints 以查看它在每个步骤中所做的事情,或者通过可视化器运行它,例如this one

当你到达yis的时候"we",你最终会这样做:

string = string.replace("we", "you")

但这将取代every we in string,包括 in went

如果你想以这种方式做事,你可能想修改每个yin list,然后join在最后将它们重新组合在一起,如下所示:

def random_sentence(sentence):
    list = sentence.split()
    for index, y in enumerate(list):
        for i in words:
            for u in i:
                if y == u:
                    mylist = i[1]
                    list[index] = mylist
    return ' '.join(list)

如果你觉得这很难理解……好吧,我也是。你所有的变量名要么是一个字母,要么是一个误导性的名称(比如mylist,它甚至不是一个列表)。i此外,当您真的只想检查第一个元素时,您正在查看。看看这是否更具可读性:

replacements = [["I", "you"], ["i", "you"], ["we", "you"], ["my", "your"], ["our", "your"]]
def random_sentence(sentence):
    words = sentence.split()
    for index, word in enumerate(words):
        for replacement in replacements:
            if word == replacement[0]:
                words[index] = replacement[1]
    return ' '.join(words)

但是,有一个更好的方法来解决这个问题。

首先,不要使用单词替换对列表,而是使用字典。然后,您可以摆脱整个循环并使其更易于阅读(也更快):

replacements = {"I": "you", "i": "you", "we": "you", "my": "your", "our": "your"}
def random_sentence(sentence):
    words = sentence.split()
    for index, word in enumerate(words):
        replacement = replacements.get(word, word)
        words[index] = replacement
    return ' '.join(words)

然后,与其尝试修改原始列表,不如构建一个新列表:

def random_sentence(sentence):
    result = []
    for word in sentence.split():
        result.append(replacements.get(word, word))
    return ' '.join(result)

那么,这result = []正是for …: result.append(…)列表推导的用途:

def random_sentence(sentence):
    result = [replacements.get(word, word) for word in sentence.split()]
    return ' '.join(result)

... 或者,由于您实际上不需要将列表用于任何目的,而是将其提供给join,因此您可以使用生成器表达式:

def random_sentence(sentence):
    return ' '.join(replacements.get(word, word) for word in sentence.split())
于 2013-04-15T10:53:31.443 回答
0
>>> words = {'I': 'you', 'i': 'you', 'we': 'you', 'my': 'your', 'our': 'your'}
>>> def random_sentence(sentence):
        return ' '.join([words.get(word, word) for word in sentence.split()])
>>> random_sentence('I have a my pet dog')
'you have a your pet dog'
于 2013-04-15T11:00:09.477 回答
0

字典/地图在这里更有意义,而不是数组数组。将您的字典定义words为:

words = {"I":"you", "i":"you", "we":"you","my":"your","our":"your"}

然后,将其用作:

def randomsentence(text):
    result = []
    for word in text.split():
        if word in words:  #Check if the current word exists in our dictionary
            result.append(words[word])   #Append the value against the word
        else:
            result.append(word)          

    return " ".join(result)

输出:

>>> randomsentence("I have a my pet dog")
'you have a your pet dog'
于 2013-04-15T10:57:11.110 回答
0

问题是string.replace替换了作为单词一部分的子字符串。您可以手动构建这样的答案:

def random_sentence(sentence):
    list = sentence.split()
    result = []
    for y in list:
        for i in words:
            if i[0] == y:
                result.append(i[1])
                break
        else:
            result.append(y)


    return " ".join(result)

注意else对应于fornot if

于 2013-04-15T10:52:53.827 回答