如何从python中的混合txt文件中读取数字

问题描述 投票:0回答:4

我有一个由文本和数字组成的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个数字元素的行。

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

我将不胜感激。谢谢。

python list text types reader
4个回答
1
投票

按行读取文件,并进行分析。跳过具有不相等的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']

1
投票

使用splitlines()函数。

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

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

Req=[]
For i in A:
    if I.isnumeric():
        Req.append(i)

0
投票

如果可以假设所需的行只有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)

0
投票

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

mport 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个或多个数字。


0
投票

因此,您正在寻找一个包含exactly四个由空格分隔并以换行符结尾的整数的子字符串。您可以使用正则表达式来找到遵循此模式的子字符串。假设您将字符串存储在变量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]]
© www.soinside.com 2019 - 2024. All rights reserved.