如何检索元素以在两个给定的txt文件之间进行匹配?

2024-04-20 00:08:31 发布

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

我在做一个项目,被困在这一部分。该项目包含一个程序,该程序匹配从两个不同文件(两个.txt)检索到的个人。如果某些心房在它们之间相同(例如,区域、可用小时数等),则它们匹配

问题是,给定文件中的个人按行和短语排序,并用逗号(名称、区域等)分隔。我必须在列表中单独转换信息,以便访问它们的元素。但是我不能。为了便于解释,txt中包含个人信息的给定部分组织如下:

功能:

...
in_file.readline()
individuals = in_file.readline().strip().replace("\n", "")
return (..., individuals) - (in tuples)

到目前为止,我只能提取出第一个个体。我不能做一个“循环”来分析剩下的部分

有什么想法吗

提前谢谢。希望我能说出我想解决的问题


Tags: 文件项目in程序txt名称区域列表
1条回答
网友
1楼 · 发布于 2024-04-20 00:08:31

首先,你能提供一些样本数据吗。其次,为什么不使用for循环? 第三,readline()通常在\n处停止,因此我们可以假设\n在您的行的末尾strip()将删除它,因此不需要替换它

我在以下两个功能中应用的一般策略是:

  1. 将文本文件读入一行数组
  2. 通过在预定义字符处拆分来提取ATributes,并将其放入dicts列表中

假设您正在运行Python 3(很抱歉我的异常处理错误):

def read_inp(file_name: str, *kwds:str) -> list:
#scans an file for Keywords and returns a list of all the lines starting with any of the given kwds
return_lines = []
try:
    with open(file_name, 'r') as f: #open file
        for line in f:
           if line.startswith(*kwds):#check if line starts with one of the keywords
               return_lines.append(
                   line.rstrip() #remove trailing whitespaces, etc.
                   )
    return return_lines    
except Exception as exception:
    pass

您可以将"="替换为属性名和属性名之间的任何字符 它的价值

def extract_attributes(lines: list, separator = ',') -> list:
#splits lines into smaller chunks and parses them to their desired data type
out_list = []
for line in lines:
    ldict = {}
    line = line.split(separator)
    for a in line:
        attribute = a.strip()
        chunks = attribute.split('=')
        try:#write chunk
            ldict[chunks[0]] = chunks[1]
        except IndexError:
            pass
    out_list.append(ldict)
return out_list

PS:我已经有了这些函数,正则表达式可能会使它们更加优雅

有关更多信息:

https://docs.python.org/3/library/functions.html#open

相关问题 更多 >