【问题标题】:Will only print empty list只会打印空列表
【发布时间】: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


【解决方案1】:

您应该在函数之间传递文件。而且 file.close() 将关闭文件并且永远不会执行,因为它在函数中..

【讨论】:

    【解决方案2】:

    检查一个单词是否是回文真的很容易:

    word[::-1] == word
    

    或者,如果您对回文的定义包括,例如,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))
    

    【讨论】:

    • 这会捕捉到以逗号/点/问号等结尾的单词吗?
    • 很遗憾,没有,因为 split() 函数只在空格上拆分所有标点符号,并且匹配测试失败。
    • 我已经写了一些可以做到这一点的东西,我需要在其中找到第二个单词,但这并没有做到这一点。
    • @quamrana 解决这个问题很简单,使用 word.strip(string.punctuation)
    猜你喜欢
    • 2015-03-16
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多