【问题标题】:Test text file for palindromes回文测试文本文件
【发布时间】:2014-05-28 01:38:07
【问题描述】:
我正在尝试获取一个文本文件,将其转换为一个列表,然后询问用户一个字长。我的函数应该打印文本文件中的所有回文。我的输出只是一个空列表。有什么指点吗?
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)
【问题讨论】:
标签:
python
file
python-3.x
io
palindrome
【解决方案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]])
【解决方案2】:
将字符串转换为字符列表不使用split() 而是:
wordlist = list(words)
【解决方案3】:
是什么让您认为您的输出是一个空列表?您忽略了printPal 的输出,不保存它(或打印它或其他)。尝试将main 更改为
def main():
size = int(input('Enter word size:'))
results = printPal(size)
print results
并确保您以后发布准确的代码。您在上述任何一行中缺少右括号,并且您没有致电 main。