我怎么只打印每5林

2024-10-01 11:20:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件("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)  

Tags: nametxtnumberdataifnameslinelocation
3条回答

一种简单的方法如下:

with open('name_data.txt', 'r') as file:

    index = 0
    for line in file:
        if index % 5 == 0:
            print(line.split()[1])
        index += 1

你可以用一行单字来理解

c = open('test.txt', 'r').readlines()

# for every fifth line extract out name and store in list
a = [i.replace('name: ', '').replace('\n', '') for i in c[::5]]

print(a) # ['Kelo', 'Miko']

您可以通过将linenumber modulo 5与一个数字进行比较来识别每五行。在您的例子中,这应该是0,因为您需要第一行和第六行、第十一行。。。(注意python以索引0开头)

要获得行号和内容,可以使用^{}在文件中迭代。在

然后要丢弃字符串的name:部分并保留后面的内容,可以使用^{}。在

一个有效的实现可以如下所示:

# Create an empty list for the names
names = []

# Opening the file with "with" makes sure it is automatically closed even
# if the program encounters an Exception.
with open('name_data.txt', 'r') as file:
    for lineno, line in enumerate(file):
        # The lineno modulo 5 is zero for the first line and every fifth line thereafter.
        if lineno % 5 == 0:
            # Make sure it really starts with "name"
            if not line.startswith('name'):
                raise ValueError('line did not start with "name".')
            # Split the line by the ":" and keep only what is coming after it.
            # Using `maxsplit=1` makes sure you don't run into trouble if the name 
            # contains ":" as well (may be unnecessary but better safe than sorry!)
            name = line.split(':', 1)[1]
            # Remove any remaining whitespaces around the name
            name = name.strip()
            # Save the name in the list of names
            names.append(name)

# print out the list of names
print(names)

您还可以将^{}与步骤参数一起使用,而不是枚举:

^{pr2}$

根据您的需要,您可以考虑使用re模块来完全解析文件:

import re
# The regular expression
group = re.compile(r"name: (.+)\nfamily name: (.+)\nlocation: (.+)\nmembers: (.+)\n", flags=re.MULTILINE)
with open(filename, 'r') as file:
    # Apply the regex to your file
    all_data = re.findall(group, file)
# To get the names you just need the first element in each group:
firstnames = [item[0] for item in all_data]

对于您的示例,firstnames将是['Kelo', 'Miko'],如果您使用[item[1] for item in all_data],那么您将得到姓氏:['Lam', 'Naiton']。 要成功使用正则表达式,必须确保它与文件布局匹配,否则将得到错误的结果。在

相关问题 更多 >