簡體   English   中英

計算txt文件中每一行的出現次數,並將其保存到Python矩陣中

[英]Count the occurance in each line from a txt file and save them into matrix in Python

我是python的新手,我的第一個任務是將.txt文件中的數據保存到矩陣中。

.txt文件包含以下數據:

0 1 1 

0

2 3 2 4  

我想讀取.txt文件,並通過計算每行中每個數字的出現將其轉換為python中的2D矩陣,並將其保存到矩陣中,其中每行都被視為一幀。

輸出會來

          c0 c1 c2 c3 c4

frame0    1     2    0    0    0

frame1    1     0    0    0    0  

frame2    0     0    2    1    1

例如,數字0在第一行出現一次,其中數字1出現兩次。

使用collections.Counter對列表中每個項目的出現進行計數,並將項目映射到字典中它們的計數:

from collections import Counter
text='''0 1 1
0
2 3 2 4'''
matrix = []
for line in text.split('\n'):
    counts = Counter(line.split())
    matrix.append([counts.get(str(i), 0) for i in range(max(map(int, counts.keys())) + 1)])
frame_size = max(map(len, matrix))
matrix = [frame + [0] * (frame_size - len(frame)) for frame in matrix]
print(matrix)

輸出:

[[1, 2, 0, 0, 0], [1, 0, 0, 0, 0], [0, 0, 2, 1, 1]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM