我有一个文本文件("name_data.txt"
),它包含以下内容:
name: Kelo
family name: Lam
location: Asia
members: Kelo, Kiko, Jil
name: Miko
family name: Naiton
location: Japan
members: Miko,Kayati
文本文件继续使用相同的模式(名称、姓氏、位置、成员)
我想打印出第一行,然后每5行打印一次,这样我就只打印了开头带有“name”的行。 然后我想要一份名单
我希望我的输出是:
^{pr2}$到目前为止,我得到了(虽然,这是错误的):
name_data= load_local_file('name_data.txt',ignore_header=False,delimiter='\t')
def __init __(name_reader):
names=list()
count=0
name_line=5
line_number=0
for name in name_data:
if line_number<5:
line_number +=1
if line_number ==5:
names.append(line_number)
一种简单的方法如下:
你可以用一行单字来理解
您可以通过将
linenumber modulo 5
与一个数字进行比较来识别每五行。在您的例子中,这应该是0
,因为您需要第一行和第六行、第十一行。。。(注意python以索引0开头)要获得行号和内容,可以使用^{} 在文件中迭代。在
然后要丢弃字符串的} 。在
name:
部分并保留后面的内容,可以使用^{一个有效的实现可以如下所示:
您还可以将^{} 与步骤参数一起使用,而不是枚举:
^{pr2}$根据您的需要,您可以考虑使用
re
模块来完全解析文件:对于您的示例,
firstnames
将是['Kelo', 'Miko']
,如果您使用[item[1] for item in all_data]
,那么您将得到姓氏:['Lam', 'Naiton']
。 要成功使用正则表达式,必须确保它与文件布局匹配,否则将得到错误的结果。在相关问题 更多 >
编程相关推荐