从txt文件中读取列表中的数字,但最多只能读取一个命令

2024-04-23 23:07:57 发布

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

这是来自实验室实验的数据(大约717行数据)。我想在python或matlab上导入并绘制它,而不是试图超越它。顺便说一句,我是新来的。。。我是个学生!你知道吗

""
"Test Methdo","exp-l Tensile with Extensometer.msm"
"Sample I.D.","Sample108.mss"
"Speciment Number","1"

"Load (lbf)","Time (s)","Crosshead (in)","Extensometer (in)"

62.638,0.900,0.000,0.00008
122.998,1.700,0.001,0.00012

more numbers : see Screenshot of more data from my file

我就是不知道怎么读这行,直到一个逗号。具体来说,我需要其中一个数组/列表的加载编号,因此,例如在第一行中,我只需要62.638(这将是我的列表/数组的第一个索引上的第一个编号)。你知道吗

我怎样才能得到一个数组/列表,一个迭代/读取列表并忽略字符串的数组/列表?你知道吗

谢谢!你知道吗

注意:我使用Anaconda+Jupyter笔记本来编写Python和Matlab(学校提供的软件)。你知道吗

编辑:好吧,我今天回家又做了一次。我以前没有处理过CSV文件,但是经过一些搜索之后,我学会了如何读取我的文件。你知道吗

import csv
from itertools import islice

with open('Blue_bar_GroupD.txt','r') as BB:
    BB_csv = csv.reader(BB)
    x = 0
    BB_lb = []
    while x < 7: #to skip the string data
        next(BB_csv)
        x+=1
    for row in islice(BB_csv,0,758):
        print(row[0]) #testing if I can read row data

好吧,这就是我被困住的地方。我想制作一个数组/列表,每行有第0个索引值。抱歉,如果我是个疯子!你知道吗

再次感谢!你知道吗


Tags: 文件csv数据infromimport列表data
3条回答

您可以跳过所有行直到第一个数据行,然后将数据解析到一个列表中供以后使用—700多行可以在内存中轻松处理。你知道吗

因此,您需要:

  • 逐行读取文件
    • 记住数字/逗号/点(==标题)之前的最后一行非空行
    • 查看行是否只有数字/逗号/点,否则增加一个跳过计数器(==data)
  • 搜索到0
  • 跳过足够多的行以获取标题或数据
  • 将其余部分读入数据结构

创建测试文件:

text = """
""
"Test Methdo","exp-l Tensile with Extensometer.msm"
"Sample I.D.","Sample108.mss"
"Speciment Number","1"

"Load (lbf)","Time (s)","Crosshead (in)","Extensometer (in)"

62.638,0.900,0.000,0.00008
122.998,1.700,0.001,0.00012
""" 
with open ("t.txt","w") as w:
    w.write(text)

一些帮助程序和跳过/读取逻辑:

import re
import csv

def convert_row(row):
    """Convert one row of data into a list of mixed ints and others.
    Int is the preferred data type, else string is used - no other tried."""
    d = []
    for v in row:
        try:
            # convert to int && add
            d.append(float(v))
        except: 
            # not an int, append as is
            d.append(v)
    return d

def count_to_first_data(fh):
    """Count lines in fh not consisting of numbers, dots and commas.
    Sideeffect: will reset position in fh to 0."""
    skiplines = 0
    header_line = 0
    fh.seek(0)
    for line in fh:
        if re.match(r"^[\d.,]+$",line):
            fh.seek(0)
            return skiplines, header_line
        else:
            if line.strip():
                header_line = skiplines
            skiplines += 1
    raise ValueError("File does not contain pure number rows!")

助手的使用/数据转换:

data = []
skiplines = 0
with open("t.txt","r") as csvfile:
    skip_to_data, skip_to_header = count_to_first_data(csvfile)

    for _ in range(skip_to_header): # skip_to_data if you do not want the headers
        next(csvfile)
    reader = csv.reader(csvfile, delimiter=',',quotechar='"')
    for row in reader:
        row_data = convert_row(row) 
        if row_data:
            data.append(row_data)

print(data)

输出(重新格式化):

[['Load (lbf)', 'Time (s)', 'Crosshead (in)', 'Extensometer (in)'], 
 [62.638, 0.9, 0.0, 8e-05], 
 [122.998, 1.7, 0.001, 0.00012]]

独行:


有了它,您就有了“干净”的数据,可以用于进一步的处理,包括头文件。你知道吗

对于可视化,您可以查看matplotlib

我建议您使用python阅读您的文件

data = []
with open('my_txt.txt', 'r') as fd:
    # Suppress header lines
    for i in range(6):
        fd.readline()
    # Read data lines up to the first column
    for line in fd:
        index = line.find(',')
        if index >= 0:
            data.append(float(line[0:index]))

指向包含第一列数据的列表

>>> data
[62.638, 122.998]

MATLAB解决方案不太好,因为您必须知道文件中的数据行数(在python解决方案中不需要知道)

n_header = 6
n_lines = 2    % Insert here 717 (as you mentioned)

M = csvread('my_txt.txt', n_header, 0, [n_header 0 n_header+n_lines-1 0])

导致:

>> M
M = 
    62.6380
    122.9980

为了清楚起见:您也可以使用MATLABstextscan函数来实现您想要的功能,而不需要知道行数,但是在我看来,python代码将是更好的选择。你知道吗

根据你的格式,你需要做3个步骤。第一,读取所有行,第二,确定要使用哪一行,最后,获取浮点数并将其分配给一个列表。你知道吗

假设你的文件名是名称.txt,请尝试:

f = open("name.txt", "r")
all_lines = f.readlines()
grid = []
for line in all_lines:
    if ('"' not in line) and (line != '\n'):
        grid.append(list(map(float, line.strip('\n').split(','))))
f.close()

网格将包含一系列列表,其中包含一组浮动。你知道吗

有趣的解释: 在“for”循环中,我搜索了双引号以消除任何字符串,因为所有字符串都是在引号之间组合的。另一个用于跳过空行。 根据您的需要,您可以随意使用列表网格。例如,要获取第一行的第一个数字,请执行

grid[0][0]

因为python的列表从0到n-1统计n个元素。你知道吗

相关问题 更多 >