簡體   English   中英

如何將 a.txt 轉換為列表列表

[英]How do I convert a .txt to a list of lists

我需要閱讀如下所示的文本文件file.txt

NaN
NaN
[       From      To Type             When  Price
0  SillyZir  0x4a34  Bid  June 18th, 2022  50000]
NaN
[       From          To Type             When  Price
0  SillyZir  Klima#3171  Bid  June 16th, 2022  60000]

我試過這段代碼

with open("file.txt") as f:
    lines = [line.rstrip() for line in f]

但我的 Output 看起來像這樣(不對)

['NaN',
 'NaN',
 '[       From      To Type             When  Price',
 '0  SillyZir  0x4a34  Bid  June 18th, 2022  50000]',
 'NaN',
 '[       From          To Type             When  Price',
 '0  SillyZir  Klima#3171  Bid  June 16th, 2022  60000]']

我想訪問列表中的列表,但代碼將“價格”之后的行分開,我不知道如何解決這個問題......

我做了一些研究,但我找不到任何有效的方法。 我對 python 有點陌生,所以我非常感謝一些幫助!

謝謝!

您可以使用帶有分支 if 語句的基本邏輯和正則表達式來拆分空格或制表符上的列表:

import re

inside = False  # to signify if we are inside a list
result = []
sublist = []

for line in lines:
    if not inside:
        if line[0] == '[':
            inside = True
            words = re.split('[ \t]+', line)
            sublist.extend(words[1:])
        else:
            result.append(line)

    else:
        words = re.split('[ \t]+', line)
        if line[-1] == ']':
            inside = False
            sublist.extend(words[:-1])
            result.append(sublist)
            sublist = []
        else:
            sublist.extend(words[:-1])

結果:

[
    'NaN',
    'NaN', 
    ['From', 'To', 'Type', 'When', 'Price', '0', 'SillyZir', '0x4a34', 'Bid', 'June', '18th,', '2022'], 
    'NaN', 
    ['From', 'To', 'Type', 'When', 'Price', '0', 'SillyZir', 'Klima#3171', 'Bid', 'June', '16th,', '2022']
]

我已經處理了列表並提取了單詞,看看結果是否是你需要的

with open('file.txt') as f:
    lis = f.read().split('\n')

result = []
for e in lis:
    if e.startswith('['):
        result.append(e.strip('[').split())
    elif e[0].isdigit():
        result.append(e[3:].strip(']').strip().split('  '))
    elif e == 'NaN':
        result.append(e)
print(result)

Output:

['NaN',
 'NaN',
 ['From', 'To', 'Type', 'When', 'Price'],
 ['SillyZir', '0x4a34', 'Bid', 'June 18th, 2022', '50000'],
 'NaN',
 ['From', 'To', 'Type', 'When', 'Price'],
 ['SillyZir', 'Klima#3171', 'Bid', 'June 16th, 2022', '60000']]

暫無
暫無

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

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