如何使用PYthon获取两行之间的文本

2024-10-02 06:35:20 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个结构如下的文本文件:

Product ID List:

ABB:
578SH8
EFC025
EFC967

CNC:
HDJ834
HSLA87
...
...

这个文件继续,许多公司的名字和Id在他们下面。然后我需要得到所选公司的ID,并将它们附加到一个列表中,在那里它们将用于搜索网站。以下是我要获取数据的当前行:

^{pr2}$

如果只有一家公司的产品标识,而没有文本,这很好用。这不适用于我的计划,然而。。。我如何让读者从(一个例子)读到下一个公司之前?我在想也许可以在文件中添加一些东西,比如ABB END来知道要剪切到哪里,但是我仍然不知道如何首先在行之间剪切。。。如果你能让我知道,那太好了!在


Tags: 文件id公司product名字结构list文本文件
3条回答

两个连续的换行符充当分隔符,因此只需在那里拆分一个数据字典:

data = {i.split()[0]: i.split()[1:] for i in open('PID.txt').read().split('\n\n')}

由于文件的结构是这样的,您可以按照以下步骤操作:

  1. 根据两个换行符\n\n拆分成一个列表
  2. 将每个列表拆分为一个换行符\n
  3. 删除包含每个公司ID的列表的第一个元素
  4. 根据公司名称的需要使用第一个元素(如上所述)(确保删除冒号)

另外,看一下regular expressions来解析这样的数据。在

with open('file.txt', 'r') as f: # open the file
    next(f) # skip the first line
    results = {} # initialize a dictionary
    for line in f: # iterate through the remainder of the file
        if ':' in line: # if the line contains a :
            current = line.strip() # strip the whitespace
            results[current] = [] # and add it as a dictionary entry
        elif line.strip(): # otherwise, and if content remains after stripping whitespace,
            results[current].append(line.strip()) # append this line to the relevant list

相关问题 更多 >

    热门问题