【问题标题】:How to read numbers from a mixed txt file in python如何从python中的混合txt文件中读取数字
【发布时间】:2020-07-07 21:54:50
【问题描述】:

我有一个由文本和数字组成的 txt 文件。它看起来像这样:

> this is a paragraph which is introductory which lasts
  some more lines 

text text text

567 45 32 468
974 35 3578 4467
325 765 355 5466

text text text
1 3 6
text text>

我需要的是存储包含 4 个数字元素的行。

当我使用读取命令时,所有元素都被读取并存储为字符串。我不确定是否可以在不先过滤的情况下将数字转换为数字。

如果有任何帮助,我将不胜感激。 谢谢。

【问题讨论】:

  • 我的回答对你有帮助吗?
  • 如果是这样,别忘了勾选有帮助的答案

标签: python list text types reader


【解决方案1】:

使用 splitlines() 函数。

A=open(your file here,'r').read().splitlines()

这将是一个列表,现在您可以提取所需的任何内容。 喜欢:

Req=[]
for i in A:
    elem = [s.isnumeric() for s in i.split(' ')]
    if len(elem) == 4 and all(elem):
        Req.append(i)

【讨论】:

  • "123 321".isnumeric() 不会计算为true,因此这不是定位带有数字的行的有效方法。您必须拆分每一行并检查每个元素的数值。
【解决方案2】:

如果你知道如何使用 python 正则表达式模块,你可以这样做:

import re

if __name__ == '__main__':

    with open(TEST_FILE, 'r') as file_1:
        for line in file_1.readlines():

            if re.match(r'(\d+\s){4}', line): 
                line = line.strip() # remove \n character
                print(line) # just lines with four numbers are printed

您的文件示例的结果是:

567 45 32 468
974 35 3578 4467
325 765 355 5466

【讨论】:

    【解决方案3】:

    逐行读取文件,并分析它们。跳过包含不等 4 个元素的行和不包含 4 个空格分隔的整数的行:

    results = []
    with open (filename) as f:
        for line in f:
            line = line.strip().split()
            if len(line) != 4:
                continue  # line has != 4 elements
    
            try: 
                numbers = map(int,line)
            except ValueError:
                continue # line is not all numbers
    
            # do something with line
            results.append(line)  # or append(list(numbers)) to add the integers
    
    print(*results, sep="\n")
    

    打印:

    ['567', '45', '32', '468']
    ['974', '35', '3578', '4467']
    ['325', '765', '355', '5466']
    

    【讨论】:

      【解决方案4】:

      如果您可以假设您需要的行只有 4 个数字,那么这个解决方案应该可以工作:

      
      nums = []
      with open('filename.txt') as f:
          for line in f:
              line = line.split()
              if len(line) == 4 and all([c.isdigit() for c in line]):
                  # use [float(c) for c in line] if needed
                  nums.append([int(c) for c in line])
      
      print(nums)
      

      【讨论】:

        【解决方案5】:

        因此,您正在寻找一个包含恰好四个整数的子字符串,这些整数由空格分隔并以换行符结尾。您可以使用正则表达式来定位遵循此模式的子字符串。假设您将字符串存储在变量s

        import re
        matches = [m[0] for m in re.findall(r"((\d+\s){4})", s)]
        

        matches 变量现在包含恰好包含四个整数的字符串。之后,您可以拆分每个字符串并根据需要转换为整数:

        matches = [[int(i) for i in s.split(' ')] for s in matches]
        

        结果:

        [[567, 45, 32, 468], [974, 35, 3578, 4467], [325, 765, 355, 5466]]
        

        【讨论】:

          【解决方案6】:

          对我来说,这听起来像是 re 模块的任务。我会这样做:

          import re
          with open('yourfile.txt', 'r') as f:
              txt = f.read()
          lines_w_4_numbers = re.findall(r'^\d+\s\d+\s\d+\s\d+$', txt, re.M)
          print(lines_w_4_numbers)
          

          输出:

          ['567 45 32 468', '974 35 3578 4467', '325 765 355 5466']
          

          解释:re.M 标志意味着 ^$ 将匹配行的开始/结束,\s 表示空格,\d+ 表示 1 个或多个数字。

          【讨论】:

            【解决方案7】:

            在这里使用正则表达式将是最强大的。我们使用 re.compile 创建一个模式,然后我们使用搜索或匹配方法来匹配字符串中的模式。

            import re
            
            p = re.compile(r'[\d]{4}') # \d matches for single digit and {4} will look for 4 continuous occurrences.
            file = open('data.txt', 'r') # Opening the file
            line_with_digits = [] 
            for line in file:  # reading file line by line
                if p.search(line): # searching for pattern in line
                    line_with_digits.append(line.strip())  # if pattern matches adding to list
            
            print(line_with_digits) 
            

            上述程序的输入文件是:

            text text text
            
            567 45 32 468
            974 35 3578 4467
            325 765 355 5466
            
            text text text
            1 3 6
            text text
            
            text  5566 text 45 text
            text text 564 text 458 25 text
            

            输出是:

            ['974 35 3578 4467', '325 765 355 5466', 'text  5566 text 45 text']
            

            希望这会有所帮助。

            【讨论】:

              【解决方案8】:

              你可以使用正则表达式:

              import re
              
              result = []
              with open('file_name.txt') as fp:
                  for line in fp.readlines():
                      if re.search(r'\d{4}', line):
                          result.append(line.strip())
              
              print(result)
              

              输出:

              ['974 35 3578 4467', '325 765 355 5466']
              

              【讨论】:

                猜你喜欢
                • 2014-07-20
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2016-05-27
                • 1970-01-01
                • 1970-01-01
                • 2015-01-28
                • 2023-03-26
                相关资源
                最近更新 更多