簡體   English   中英

如何在python中將字符逐個讀取為矩陣文件?

[英]How to read file into matrix character by character in python?

在Python中,我有一個像這樣的文件:

foo
fo
f
foo
foooo

我想將其讀入如下矩陣:

[['f', 'o', 'o', ' ', ' '],
 ['f', 'o', ' ', ' ', ' '],
 ['f', ' ', ' ', ' ', ' '],
 ['f', 'o', 'o', ' ', ' '],
 ['f', 'o', 'o', 'o', 'o']]

這樣每個單獨的列表都具有相同的長度,並且該長度是最長列表的長度,並填充空格以達到該長度。

到目前為止,這是我的代碼:

with open('data.txt', 'r') as myfile:
    data=myfile.read()

for c in data:
    ????

你可以這樣建造

text = open(file_name).read()
lst = text.split('\n')
print [list(i+' '*(len(max(lst))-len(i))) for i in lst]

獲取在該maimum lenth谷lst和當前淡水河谷獲得substarcted值,並獲得addup ' '領域,

結果

[['f', 'o', 'o', ' ', ' '],
 ['f', 'o', ' ', ' ', ' '],
 ['f', ' ', ' ', ' ', ' '],
 ['f', 'o', 'o', ' ', ' '],
 ['f', 'o', 'o', 'o', 'o']]

如您所知,第一步是找到最大長度的字符串:

with open("file.txt", 'r') as f:
    lines = f.readlines()
    max_len = max(map(len,lines))

一旦有了這個,就可以通過使用format()函數填充字符串來構建數組,因此對於每一行,

modified_line = "{:{max_len}}".format(original_line, max_len)

這將在一個max_len長(左對齊)的字符串內填充original_line format函數的語法可能會有些棘手,因此我為您提供了一個很好的開端,但是其余的很簡單,我會留給您。

使用maxstr.ljust函數的簡短解決方案:

with open('data.txt', 'r') as myfile:
    lines = myfile.readlines()
    max_len = len(max(lines, key=len))
    result = [list(l.ljust(max_len, ' ')) for l in lines]

print(result)

暫無
暫無

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

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