我需要一个Python程序,它可以从文件中读取并在屏幕上打印出标题词。我开始这样做了,这就是我到目前为止所做的:
info = open("info.txt", "r")
lines = info.readlines()
def function():
while True:
if lines.istitle():
print (lines)
if not lines.istitle():
break
但它似乎不起作用。有什么建议吗?
答案 0 :(得分:2)
info = open("info.txt", "r")
res = [line for line in info if line.istitle()]
print res
info.close()
或更简单
info = open("info.txt", "r")
for line in info:
if line.istitle():
print line
info.close()
答案 1 :(得分:2)
您可以定义一个从文件中产生标题行的函数:
def titles(filename):
with open(filename) as info:
for line in info:
if line.istitle():
yield line
然后将它们打印出来:
for title in titles('info.txt'):
print(title)
答案 2 :(得分:0)
这是一种方法:
info = [ln.strip() for ln in open("info.txt") if ln.istitle()]
答案 3 :(得分:0)
这类似于@ user3238855的答案,但我使用的是Python 3的sub: ['a', 'b', 'c']
command:
params:
cmd1:
type: string
enum : # Get the list defined in 'sub'
description: Exclude commands from the test list.
cmd2:
type: string
enum: # Get the list defined in 'sub'
函数,print()
而不是理解,而不是保存对filter()
行的引用。
list