在fi中搜索反向字符串

2024-04-25 09:30:39 发布

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

我试图做一个脚本,看看里面的一个文件,其中包含了我的语言(每行1个字),阅读它,并检查是否在该文件中的每一个单词是在文件中的反向,基本回文和半回文

words = open('AllWords.txt', 'r')

for line in words:
    reverse = line[::-1]
    if reverse in words:
        print(reverse)
    if reverse not in words:
        continue

然而,在文件中的第一个单词(不是单词的反方向)之后,它似乎停止了迭代。你知道吗

有人知道我该怎么解决这个问题吗?你知道吗


Tags: 文件intxt脚本语言forifline
3条回答

如果你的文件中有大量的单词,那么这个过程将会非常缓慢。使用集合操作可以更快地获得结果:

words = open("Allwords.txt").read().split("\n")
palindromes = set(words).intersection(w[::-1] for w in words)
for palindrome in palindromes: print(palindrome)
words = open('AllWords.txt', 'r').readlines()

for line in words:
    reverse = line[::-1]
    if reverse in words:
        print(reverse)

问题是word是一个迭代器,检查reverse in words会耗尽它。因此,对于for循环的下一次迭代,没有其他可用元素(迭代器已用尽),因此它停止迭代。你知道吗

您可以使用listset代替:

words = set(map(str.rstrip, open(...).readlines()))

然后执行剩下的代码,正如您已经指出的那样。你知道吗

如果顺序很重要,那么可以使用list进行迭代,使用set进行检查(集合的成员资格测试是O(1)):

with open(...) as fh:
    words = [x.rstrip() for x in fh]
word_set = set(words)
for word in words:
    if word[::-1] in word_set:
        print(word)

您也可以使用两个集合,因为回文是两个集合的交集,一个用于单词,另一个用于反向单词:

with open(...) as fh:
    words = set(map(str.rstrip, fh))
words_reversed = set(x[::-1] for x in words)
palindromes = words & words_reversed

相关问题 更多 >

    热门问题