简体   繁体   English

逐行读取txt文件,然后获取每行的长度

[英]Reading txt file line by line, and then getting each line's length

The data.txt includes elements of arrays, separated by semicolons. data.txt 包含数组元素,以分号分隔。 Each line is supposed to be read as one array.每一行都应该被读取为一个数组。

data.txt数据.txt

4; -9; -1; 9; -1; -3; 8; 8; 0; -9; -8 
7; 6; 5; -6; 5; -4; 2; 1; -1; -6; 0; 3; -7; 9; 9; 6; -5; -8; 1; -8; -1; -1
-8; -6; -6; -5; -6; -8; -4; -2; 8; -3; 3; 6; 4; -9; 10; 2; -4; 7; -5; 0; -3; 7; -7; 6; -10; 8; -9; 9; 2; -1; -6; 6; -5; 8; 0; 3; 6; -10; -2; 8; -6; -5; 9; 10
1; 7; -6; 7; 6; 2; 9; 2; 3; 1; 0; 8; 5; 2; 4; 9; -10; 3; -9; 9; -2; 8; -1; 4; -4; -3; -10; -2; -9; -5; 7; 9; -4; 6; 10; -1; -8; 10; -2; 2; -9; 2; -2; 2; 3; 10; 6; 3; -3; -5; -4; 6; -4; -2; 2; -5; 4; -8; 0; -2; -5; -4; 3; 4; -6; -10; 3; -5; -10; -3; 4; 10; 10; 5; -5; 0; 10; 2; 9; 7; -8; -2; 10; 4; 10; 9; 3; -7; 
-3; -9; 5; -10; -3; 3; -7; 8; 8; 1; 8; -10; 0; -6; -10; 3; -10; 1; -1; -2; 10; 3; -3; -10; 9; -3; 9; 6; 2; 3; 6; -10; 1; -4; -1; 8; 5; 7; -6; -9; 1; -6; -9; 8; -7; -5; -4; -1; 10; 8; -10; -3; -10; -5; 1; 0; 5; -6; 7; 3; -8; -9; -8; -6; 3; 4; 0; 5; -9; 8; 7; -2; 0; -7; 7; 1; -2; 10; -7; 3; 10; -10; 5; 3; 3; -7; -3; -6; -3; -4; -6; 4; -1; 10; 7; 1; 5; 6; 0; -8; -6; -5; 6; 9; 2; 2; -8; 3; 2; -8; 1; -2; -10; 3; 8; 3; 6; 2; -5; 6; -8; -6; 10; -1; -7; 9; 3; -8; -9; 3; -2; 2; -9; -6; -2; -9; -4; 7; -6; 3; -5; 5; 4; 6; -7; 0; -4; 8; -9; 3; -1; -7; -9; 1; -5; -3; -2; 0; 4; 4; -3; -5; -8; -3; 0; -1; 5; -9; 5; 2; 4; 3; 3; 4; 10; -2

Here's my first attempt:这是我的第一次尝试:

f = open("data.txt", "r")
a = [f.readline()]

And I am completely stuck.我完全被困住了。 I noticed that the semicolons are required to be converted to commas as well.我注意到分号也需要转换为逗号。

I'm assuming that you want to pack each line into an list (= array) of integers and collect all those arrays into a larger container.我假设您想将每一行打包到一个整数列表(= 数组)中,并将所有这些数组收集到一个更大的容器中。 Here's a version which each step explained:这是每个步骤解释的版本:

# Use the context manager 'with' to make sure the file gets closed after
# you're done
with open('data.txt', 'r') as file:
    # Initialize container for the arrays
    arrays = []
    # Loop (iterate) over the lines of the file
    for line in file:
        # Remove whitespace at the ends (including \n = newline)
        line = line.strip()
        # Remove ';' from the end (at least in one line)
        line = line.rstrip(';')
        # Split the line on the ';'s into a list of strings representing
        # the numbers
        numbers_str = line.split(';')
        # Convert the list of string-numbers into a list (array) of integers
        array = [int(number_str) for number_str in numbers_str]
        # Append the newly created array to the array container
        arrays.append(array)
print(arrays)

A more compact and "pythonic" version:一个更紧凑和“pythonic”的版本:

with open('data.txt', 'r') as file:
    arrays = [
        [int(number) for number in line.strip().rstrip(';').split(';')]
        for line in file.readlines()
    ]
print(arrays)

EDIT : Determining the lengths:编辑:确定长度:

Line length:线长:

with open('data.txt', 'r') as file:
    for i, line in enumerate(file.readlines(), start=1):
        print(f'Length of line {i}: {len(line.rstrip())}')

Number of integers (run after calculating arrays):整数数(在计算数组后运行):

for i, array in enumerate(arrays, start=1):
    print(f'Number of integers in line {i}: {len(array)}')

Your current code will construct a list with the whole line as its only item.您当前的代码将构建一个以整行作为唯一项的列表。 You must split the line and then convert each element to an integer.您必须拆分该行,然后将每个元素转换为整数。 Try this:尝试这个:

a = [int(s) for s in f.readline().split(";")]

To read all lines, you can use the following method:要读取所有行,您可以使用以下方法:

with open("data.txt", "r") as f:
    for line in f:
        a = [int(s) for s in line.split(";")]

Here's the simple way to find out the length of each line.这是找出每行长度的简单方法。

arr = []
arr_len = []
with open('xyz.txt') as f:
    #iterate thru each line in the file
    for line in f:

        #for each line, strip the end of line and any spaces, then split by ';'
        x = line.strip('\n').strip().split(';')

        #store the contents into an array for future use
        arr.append([int(i) for i in x])

        #store the length of each line into an array
        arr_len.append(len(x))

print ('The number of elements in each line are:', arr_len)

The output will be as follows:输出如下:

The number of elements in each line are: [11, 22, 44, 88, 176]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM