繁体   English   中英

Python - 从 txt 中读取空格和 | 分隔以将值添加到列表

[英]Python - Read lines from txt that are space and | delimited to add values to list

我有一个文本文件,它似乎既是空格又是 pipe 分隔的。

                                                                   Test Codes

 ABCBBA        3       -1189.59   |   ABCCHOICE     1          22.56    |    ABCELECT     31       13516.72   |    ABCFED       14        9070.74
 ABCHMOBLUE   38       13183.27   |   DCMCDNY       1           8.86    |    ABCMEDHMO     7        6189.83   |    ABCMEDPPO    17        6730.53

我需要提取的是任何以 D 开头的代码和相应的值。 所以使用上面的例子,我想要的 output 将是:

Code     Total
DCMCDNY  8.86

当我使用:

for index, line in enumerate(lines):
if "Test Codes" in line:
    print(re.split(r'\s{2,}',lines[index+2].lstrip()))
if "Test Codes" in line:
    print(re.split(r'\s{2,}',lines[index+3].lstrip()))

我得到以下 output:

['ABCBBA', '3', '-1189.59', '|', 'ABCCHOICE', '1', '22.56', '|', 'ABCELECT', '31', '13516.72', '|', 'ABCFED', '14', '9070.74']
['ABCHMOBLUE', '38', '13183.27', '|', 'DCMCDNY', '1', '8.86', '|', 'ABCMEDHMO', '7', '6189.83', '|', 'ABCMEDPPO', '17', '6730.53']

但是,我不确定这是否是最具可扩展性的方法,或者我如何从列表中提取代码和值。

我将从拆分“|”开始特点。

 candidates = {}  # To store results
 lines = data_file.readlines()
 for line in lines:
    strip_pipe = line.strip("|")

    # Process the list from split for whitespace delimiters
    for candidate in strip_pipe:
        stripped = candidate.strip()  # Removes begin and end whitespace

        # Check if the first item has the letter "D"
        if stripped[0] == "D":
           split_space = stripped.split(" ")
           candidates.update({"Code": split_space[0], "Total": split_space[-1]})

    

根据您上面的示例数据,此代码将为您提供 output

{'DCMCDNY': '8.86'}

现在,虽然这至少为您提供了所需的 output,但对于大数据而言,它可能不是最具可扩展性的。 希望它能激发您的一些想法来改进它并使其满足您的需求!

暂无
暂无

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

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