python - 从文件中读取行时继续使用值,直到列表中的下一个键 - python

标签 python python-3.x list iterator

我有一个像这样的值列表:

names_needed = ['PCC', 'PSP', 'ASP']

此外,我正在读取 .txt 文件,以根据上面的列表提取一些值:

PCC WITH NOTHING
ABB,CAI null V00011 11/06/18
ANDERS,SAND null V000103 07/10/17
KUCHEN,SARA null V00011 03/21/19 

PSP SECONDARY
MUNCH,TORY null V000113 04/08/19 
ACOSTA,AD null V00010 06/19/17 

PCC WITH SOEMTHING
BEC,RUMA null V00011 04/17/19 
BECE,COR null V00010 10/25/16 
TORRE,M null V0001143 06/06/19

ASP HAS IT
XON,ANDREA null V00011 03/27/19

PSP Wanted
NICK,SON null V00011 05/20/19
JUARE,SABIO null V00011 04/02/19

从这个文本文件中,我想读取每一行,然后检查其中一个键值是否存在,并将所有数据放入该关键字后面的列表中。

类似这样的事情:

PCC:
[ABB,CAI null V00011 11/06/18
ANDERS,SAND null V000103 07/10/17
KUCHEN,SARA null V00011 03/21/19 
BEC,RUMA null V00011 04/17/19 
BECE,COR null V00010 10/25/16 
TORRE,M null V0001143 06/06/19]

PSP:
[MUNCH,TORY null V000113 04/08/19 
ACOSTA,AD null V00010 06/19/17 
NICK,SON null V00011 05/20/19
JUARE,SABIO null V00011 04/02/19]

ASP:
[XON,ANDREA null V00011 03/27/19]

结果可以是列表的列表,也可以是值的字典。我尝试了以下方法:

names_needed = ['PCC', 'PSP', 'ASP']

## Key word list
key_word_list = []

## Empty list to save all lines
all_lines = []

## Open text file
read_text_file = r'text_file.TXT'

### Open the file
with open(read_text_file) as f:
    # For each line
    for line in f:
        # Strip off white space characters
        stripped_line = line.strip()

        # Iterate the list of key values   **** HERE is WHERE I AM ITERATING KEY WORD
        for i in names_needed:
            if i in stripped_line:
                key_word_list.append(i)
                all_lines.append(stripped_line)

            else:
                break

这没有给我想要的结果。我似乎无法理解当前关键字和下一个关键字之间的界限。

最佳答案

解决此问题的另一种方法是识别哪些行包含键,并将以下所有行附加到字典中的相应键中。您的文件非常适合此解决方案,因为关键行中的任何位置都没有斜杠:

def is_key(line):
    return '/' not in line

输出将以字典的形式出现,将每个键映射到属于它的行列表:

keywords = {key: [] for key in names_needed}

现在您可以按如下方式使用这些定义:

key = None
with open(read_text_file) as f:
    for line in f:
        line = line.strip()
        if is_key(line):
            key = line.split()[0]
        elif key in keywords:
            keywords[key].append(line)

您现在可以通过按键访问关键字:

for key, lines in keywords.items():
    print(f'{key}:')
    print(f'    {"\n    ".join(lines)}')
    print()

关于python - 从文件中读取行时继续使用值,直到列表中的下一个键 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57098430/

相关文章:

python - 如何在Python中全局使用对象?

python - 如何计算列表中所有数字的索引次方

list - Flex4列表项双击事件

python - 根据值获取列表的列表索引范围

python - 从 Python 和 impacket 获取 TCP 数据包有效载荷

python - python 中的简化扫雷递归 : why is this code not succeeding?

python - 根据长度将数据帧拆分为相对均匀的 block

python - 仅使用 Pandas 转换某些行

python - 在迭代元组时获取 "TypeError: ' datetime.date' 对象不可迭代”(将元组转换为列表)

python - python 中的 input() 和\n 字符