在字符串中查找单词的semordnilap(反字谜)

2024-09-30 00:24:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用一个字符串输入,比如一个句子,然后找到所有在句子中有相反单词的单词。到目前为止我有:

s = "Although he was stressed when he saw his desserts burnt, he managed to stop the pots from getting ruined"

def semordnilap(s):
    s = s.lower()
    b = "!@#$,"
    for char in b:
        s = s.replace(char,"")
    s = s.split(' ')

    dict = {}
    index=0
    for i in range(0,len(s)):
        originalfirst = s[index]
        sortedfirst = ''.join(sorted(str(s[index])))
        for j in range(index+1,len(s)):
            next = ''.join(sorted(str(s[j])))
            if sortedfirst == next:
                dict.update({originalfirst:s[j]})
        index+=1

    print (dict)

semordnilap(s)

所以这在很大程度上是有效的,但是如果你运行它,你可以看到它也把“他”和“他”作为一个字谜配对,但这不是我要找的。任何关于如何修复它的建议,以及是否有可能使运行时更快,如果我输入一个大的文本文件。你知道吗


Tags: inforindexlenrange单词dict句子
1条回答
网友
1楼 · 发布于 2024-09-30 00:24:02

您可以将字符串拆分为单词列表,然后比较所有组合的小写版本,其中一个组合是相反的。下面的示例使用re.findall()将字符串拆分为单词列表,并使用itertools.combinations()对它们进行比较:

import itertools
import re

s = "Although he was stressed when he saw his desserts burnt, he managed to stop the pots from getting ruined"

words = re.findall(r'\w+', s)
pairs = [(a, b) for a, b in itertools.combinations(words, 2) if a.lower() == b.lower()[::-1]]

print(pairs)
# OUTPUT
# [('was', 'saw'), ('stressed', 'desserts'), ('stop', 'pots')]

编辑:我仍然喜欢上面的解决方案,但根据您的意见,这样做没有导入任何软件包,见下文。但是,请注意,这种方式使用的str.translate()可能会产生意想不到的后果,这取决于文本的性质(例如从电子邮件地址中剥离@)-换句话说,您可能需要更仔细地处理标点符号。另外,我通常会import string并使用string.punctuation而不是传递给str.translate()的标点字符的文本字符串,但是为了满足您在不导入的情况下执行此操作的请求,下面避免了这种情况。你知道吗

s = "Although he was stressed when he saw his desserts burnt, he managed to stop the pots from getting ruined"

words = s.translate(None, '!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~').split()
length = len(words)
pairs = []
for i in range(length - 1):
    for j in range(i + 1, length):
        if words[i].lower() == words[j].lower()[::-1]:
            pairs.append((words[i], words[j]))

print(pairs)
# OUTPUT
# [('was', 'saw'), ('stressed', 'desserts'), ('stop', 'pots')]

相关问题 更多 >

    热门问题