gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:23:52 24 4
gpt4 key购买 nike

我正在尝试输入一个字符串,例如一个句子,并找出句子中所有具有反向词的单词。到目前为止我有这个:

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)

所以这在大多数情况下都有效,但如果您运行它,您会看到它还将“他”和“他”配对为一个变位词,但这不是我要找的。关于如何修复它的任何建议,以及是否可以使运行时间更快,如果我要输入一个大文本文件。

最佳答案

您可以将字符串拆分成一个单词列表,然后比较所有组合的小写版本,其中一个组合是相反的。以下示例使用 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')]

关于python - 在字符串中查找单词的 semordnilap(反向字谜),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53879197/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com