我正在遍历.txt文件并尝试在其中找到回文短语,但是当我运行此文件时,它只会打印一个空列表。
file = open("dictionary.txt", "r")# Load digital dictionary as a list of words
def find_palingram():
palingram_list = [] # Start an empty list to hold palingrams
for word in file: # For word in list
word = word.split()
end = len(word) # Get length of word
rev_word = word[::-1]
if(end > 1):#If Length > 1
for i in range(end): # Loop through the letters in the word
"""If reversed word fragment at front of word is in word list and letters after form a
palindromic sequence"""
if(word[i:] == rev_word[:end-i] and rev_word[end-i:] in file):
palingram_list.append(word, rev_word[end-i:])#Append word and reversed word to palingram list
"""If reversed word fragment at end of word is in word list and letters
before form a palindromic sequence"""
if(word[:i] == rev_word[end-i:] and rev_word[:end-i] in file):
palingram_list.append(rev_word[:end-i], word) # Append reversed word and word to palingram list
return palingram_list
file.close()
# Sort palingram list alphabetically
palingram = find_palingram()
palingram_sorted = sorted(palingram)
print(palingram_sorted)
print(file.read())
检查单词是否为回文真的很容易:
word[::-1] == word
或者,如果您包括palindrom的定义,例如,Eve
:
word_lower = word.lower()
word_lower[::-1] == word_lower
因此,您的程序可以简化为:
def find_palindroms(text):
palindrom_list = []
for line in text:
for word in line.rstrip().split():
word_lower = word.lower() # might be unnecessary
if word_lower[::-1] == word_lower:
palindrom_list.append(word)
return palindrom_list
with open("dictionary.txt", "r") as file:
print(find_palindroms(file))
您应该在函数之间传递文件。此外,file.close()将关闭文件,并且由于其在函数中而将永远不会执行。