我试着用一个字符串输入,比如一个句子,然后找到所有在句子中有相反单词的单词。到目前为止我有:
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()
对它们进行比较:编辑:我仍然喜欢上面的解决方案,但根据您的意见,这样做没有导入任何软件包,见下文。但是,请注意,这种方式使用的
str.translate()
可能会产生意想不到的后果,这取决于文本的性质(例如从电子邮件地址中剥离@
)-换句话说,您可能需要更仔细地处理标点符号。另外,我通常会import string
并使用string.punctuation
而不是传递给str.translate()
的标点字符的文本字符串,但是为了满足您在不导入的情况下执行此操作的请求,下面避免了这种情况。你知道吗相关问题 更多 >
编程相关推荐