测试文字文件的回文

时间:2014-05-28 01:38:08

标签: python file python-3.x io palindrome

我正在尝试获取文本文件,将其转换为列表,然后询问用户字长。我的函数应该打印文本文件中的所有回文。我的输出只是一个空列表。有什么指针吗?

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)

3 个答案:

答案 0 :(得分:1)

你可以这样做:

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)

如果您愿意,可以减少到一行:

print([word for word in (line.strip() for line in open(file_name, 'r')) 
               if len(word)==size and word==word[::-1]])

答案 1 :(得分:0)

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

wordlist = list(words)

答案 2 :(得分:0)

是什么让您认为您的输出是一个空列表?您通过不保存(或打印或其他)来忽略printPal的输出。尝试将main更改为

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

确保您将来发布准确的代码。您在上述其中一行上错过了一个右括号,而且您没有打电话给main