【发布时间】:2020-06-13 05:52:09
【问题描述】:
我正在遍历一个 .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())
【问题讨论】:
-
顺便说一句,您应该真正将文件传递给函数,而不是依赖文件是全局的。而且 file.close() 永远不会执行,因为它在函数中,但在返回之后。
标签: python list for-loop io append