查找句子中也存在反向的字符串

时间:2019-04-25 06:12:53

标签: python python-3.x

我需要在一个句子中找到该字符串,该句子的反向词也出现在同一句子中,并返回该字符串。

假设句子是:

  

幻觉从来没有变成真正的清醒,我可以看到完美的天空ee撕裂了你,我已经被撕裂了一点。

在这里我们可以看到"see"的反面为"ees"

因此输出应为"see"

请指导我该怎么做。

2 个答案:

答案 0 :(得分:0)

您可以尝试一下。

mystr = "illusion never changed into something real wide awake and i can see the perfect sky ees torn you are a little late I'm already torn"

def reverse(word):
    letter = list(word)
    length = len(letter)
    y = []
    for x,w in enumerate(letter):
        y.append("".join(letter[(length-1)-x]))
    return("".join(yy for yy in y))


words = mystr.split()
for word in words:
    if (reverse(word)) in words and len(word) > 1:   # len(word)>1 is for ignoring a word that contains only one letter, e.g. 'I' and 'a'.
        print ("'" + word + "' is the reverse of '" + reverse(word) + "'")

输出:

'see' is the reverse of 'ees'
'ees' is the reverse of 'see'

您也可以按照@Nuhman的建议尝试更简单的一种。

mystr = "illusion never changed into something real wide awake and i can see the perfect sky ees torn you are a little late I'm already torn"

words = mystr.split()
for word in words:
    if word[::-1] in words and len(word) > 1:
        print ("'" + word + "' is the reverse of '" + reverse(word) + "'")

输出:

'see' is the reverse of 'ees'
'ees' is the reverse of 'see'

答案 1 :(得分:0)

使用word[::-1]反转单词,如果单词列表中存在反转,则另存一个list

hello = "illusion never changed into something real wide awake and i can see the perfect sky ees torn you are a little late I'm already torn"

words = hello.split(" ")

reverse_words = []
for word in words:
    if word[::-1] in words and len(word)>1 and word[::-1] not in reverse_words:
        reverse_words.append(word)

print(reverse_words)

输出:

['see']