测试文本文件的回文

2024-09-30 20:38:34 发布

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

我试图获取一个文本文件,将其转换为一个列表,然后要求用户输入单词长度。我的函数应该打印文本文件中的所有回文。我的输出只是一个空列表。有什么建议吗?在

def main():
size = int(input('Enter word size:')
printPal(size)

def readFile():
L = open('scrabble_wordlist.txt', 'r')
words = L.read()
L.close()
while ' ' in words:
    words.remove(' ')
wordlist = words.split()
return(wordlist)

def printPal(size):
L = readFile()
results = []
for word in L:
    if isPal(word) and len(word) == size:
        results.append(word)
return(results)

def isPal(word):
return word == reversed(word)

Tags: 用户in列表sizereturndef单词results
3条回答

您可以这样做:

size = int(input('Enter word size:')) # Use raw_input('..' ) on Python 2!!!

pals=[]
with open('/usr/share/dict/words', 'r') as f:
    for word in f:
        word=word.strip()                          #remove CR and whitespace
        if len(word)==size and word==word[::-1]:   #str[::-1] reverses a string
            pals.append(word)                      # save the palidrome

print(pals)

如果您愿意,可以将其简化为一行:

^{pr2}$

将字符串转换为字符列表不会使用split()

wordlist = list(words)

是什么让你认为你的输出是一个空列表?您忽略了printPal的输出,因为没有保存它(或打印它或其他任何东西)。尝试将main更改为

def main():
  size = int(input('Enter word size:'))
  results = printPal(size)
  print results

并且确保你以后发布的代码是准确的。您在上面的一行中缺少右括号,并且没有调用main。在

相关问题 更多 >