【问题标题】:How do I only print every 5th line我如何只打印每 5 行
【发布时间】:2016-12-11 02:57:39
【问题描述】:

我有一个包含以下内容的文本文件 ("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 行打印一次,所以我只打印开头带有“名称”的行。 然后我想要一个名字列表

我希望我的输出是:

["Kelo","Miko"]

到目前为止,我得到了(虽然是错误的):

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)  

【问题讨论】:

    标签: python printing lines


    【解决方案1】:

    您可以通过将linenumber modulo 5 与数字进行比较来识别每五行。在您的情况下,这应该是0,因为您想要第一行和第 6 行、第 11 行,...(请注意,python 以索引 0 开头)

    要获取行号以及内容,您可以使用enumerate 遍历文件。

    然后要丢弃字符串的name: 部分并保留后面的内容,您可以使用str.split()

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

    # 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)
    

    您也可以使用带有 step 参数的 itertools.islice 来代替枚举:

    from itertools import islice
    
    with open('name_data.txt', 'r') as file:
        for line in islice(file, None, None, 5):
            ... # like above except for the "if lineno % 5 == 0:" line
    

    根据您的需要,您可以考虑使用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']。 要成功使用正则表达式,您必须确保它真正匹配您的文件布局,否则您会得到错误的结果。

    【讨论】:

      【解决方案2】:

      你可以用列表理解在一行中做到这一点

      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']
      

      【讨论】:

        【解决方案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
        

        【讨论】:

        • 您好 tom_1230,感谢您的评论。我尝试打印(行)并且输出作为回溯返回: return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range (128) ;你知道那是什么意思吗?
        • 该代码对我来说完美无缺,也许是文本文件编码搞砸了。创建一个新的 .txt 文件并复制您在原始问题中指定的输入,看看是否可行。
        • 我还更新了答案中的代码,只是意识到您只想打印名称而不是整行。
        • 请注意,file.close() 在这里不是必需的。 with 上下文管理器会为您执行此操作。
        【解决方案4】:

        假设name_data是文件中的行列表,你可以这样做

        names = []
        for i in range(1, len(name_data), 5):
            names.append(name_data[i].split(":")[1].strip())
        

        【讨论】:

          【解决方案5】:

          有一个name_data.txt 文件,其数据如下: 1 2 3 4 5 6 7 8 9 10

          以下是打印第一行和每 5 行的方法:

          content = [line.rstrip('\n') for line in open('name_data.txt')]
          names = []
          limit = 4
          fp = open("name_data.txt")
          names.append(content[0])
          for i, line in enumerate(fp):
              if i == limit:
                  names.append(line)
                  limit += 5
          fp.close()
          print(names)
          

          结帐http://shortcode.pro/code/read-txt-file-and-print-first-and-every-5th-line/

          【讨论】:

            【解决方案6】:

            您可以使用正则表达式 - Python 的模块是 re

            然后name_data.txt 是:

            name: Kelo
            family name: Lam
            location: Asia
            members: Kelo, Kiko, Jil
            
            name: Miko
            family name: Naiton
            location: Japan
            members: Miko,Kayati 
            

            获取名称很简单:

            import re
            
            def get_names():
            
                with open('name_data.txt', 'r') as f:
                    print(re.findall(r'^name:\s*(\w+)', f.read(), flags=re.MULTILINE))
            
            if __name__ == '__main__':
            
                get_names()
            

            注意多行标志设置 - 当设置为全局时,正则表达式也会匹配带有family name: ... 的行。 在交互模式下查看正则表达式here

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2017-03-28
              • 2020-04-13
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2018-11-09
              • 1970-01-01
              相关资源
              最近更新 更多