简体   繁体   中英

searching for reverse string in an file

I am trying to make a script that looks inside a file that contains all words of my language (1 word per line), read it and checks if every single word in that file is in reverse in the file, basicly palindromes and semi-palindromes

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

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

However it seems that after the first word in the file (which is not reverse in words) it stops iterating.

Does anyone know how I could fix this?

The problem is that word is an iterator and the check reverse in words exhausts it. So for the next iteration of the for loop there is no further element available (the iterator is exhausted) and so it stops iterating.

You could use a list or set instead:

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

Then perform the rest of the code as you've already indicated.

If order matters then you can use a list for the iteration and a set for the check (membership tests for sets are 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)

You can also use two sets since the palindromes are the intersection between two sets, one for words and one for reversed words:

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

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

The process is going to be quite slow if you have a large number of words in your file. You could get results much faster using set operations:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM