gpt4 book ai didi

python - 在终端中显示标题的更 Pythonic 方式

转载 作者:行者123 更新时间:2023-12-01 04:18:05 29 4
gpt4 key购买 nike

我编写了一个程序来读取数据文件并用它们做一堆与这个问题无关的废话。用户输入标题占多少行后,读取时会自动跳过标题。

如果需要,我内置了一些功能来在终端中显示标题。这是我用来执行此操作的实用但看起来很白痴的代码片段:

filename = (raw_input("Which file are we loading?  "))
with open(filename) as myfile:
head = 'head'
aline = myfile.readline()
bline = myfile.readline()
cline = myfile.readline()
dline = myfile.readline()
eline = myfile.readline()
fline = myfile.readline()
gline = myfile.readline()
hline = myfile.readline()
iline = myfile.readline()
jline = myfile.readline()
kline = myfile.readline()
lline = myfile.readline()
mline = myfile.readline()
nline = myfile.readline()
oline = myfile.readline()
pline = myfile.readline()
qline = myfile.readline()
rline = myfile.readline()
sline = myfile.readline()
tline = myfile.readline()
header = input("How many header lines? (Type ``head`` to see the first 20 lines) ")
if header == head:
print ' 1 | ' + aline,
print ' 2 | ' + bline,
print ' 3 | ' + cline,
print ' 4 | ' + dline,
print ' 5 | ' + eline,
print ' 6 | ' + fline,
print ' 7 | ' + gline,
print ' 8 | ' + hline,
print ' 9 | ' + iline,
print '10 | ' + jline,
print '11 | ' + kline,
print '12 | ' + lline,
print '13 | ' + mline,
print '14 | ' + nline,
print '15 | ' + oline,
print '16 | ' + pline,
print '17 | ' + qline,
print '18 | ' + rline,
print '19 | ' + sline,
print '20 | ' + tline,
header = input("How many header lines? ")

这适本地给出了:

How many header lines? (Type ``head`` to see the first 20 lines)  head
1 | ------------------------------------------------------------------------------------------------------------------------------------------------
2 | K-KIDS GOLD LIST
3 | ------------------------------------------------------------------------------------------------------------------------------------------------
4 |
5 | N = 1048 K dwarfs within 50 parsecs
6 |
...
...
...
20 | stuff

是否有更有效且“Pythonic”的方法来解决这个问题?或者我的已经达到预期的水平了吗?

干杯!

最佳答案

不确定 head 和 header 逻辑,但您可以使用 itertools.islice 拉出前 header_length 行和 str .join 连接输出:

from itertools import islice

filename = raw_input("Which file are we loading? "))
# ask user how many header lines
header_length = int(raw_input("Enter amount of header lines"))

with open(filename) as myfile:
# get the first header_length lines in a list
head = list(islice(myfile, header_length))
header = raw_input("How many header lines? (Type ``head`` to see the header lines)")
# if user types head
if "head" == header:
# use enumerate to get the line numbers/index in list
# the str.join the lines formatting index | line
print("".join(["{} | {}".format(i, line) for i, line in enumerate(head,start=1)]))

关于python - 在终端中显示标题的更 Pythonic 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34076403/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com