从3个不同的文件中读取数据,并使用一段数据在所有文件中搜索另一段数据

2024-03-29 10:01:25 发布

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

我有三个不同的文件从中读取文本。每个文件包含两个不同的数据点。你知道吗

例如,第一个文件包含姓名和电话号码,第二个文件包含姓名和社交,第三个文件包含社交和收入。你知道吗

我希望用户能够输入一个电话号码,并且程序能够吐出与该号码相关的人的所有其他已知数据(即社交、姓名、收入)。你知道吗

我输入了文件并创建了4个不同的列表,然后我的想法是告诉程序类似于,“如果‘phone’列表中的电话号码,从下一个列表中获取相应的索引值,依此类推。”但我的部分问题是,我不必在每个列表中为每个电话号码都有一个对应的值,所以我不确定使用列表的索引是最好的方法,因为索引值不一定是成对的。你知道吗

我肯定有更好的方法来解决这个问题,但我只是不确定我知道什么样的工具可以让我到达那里。。。你知道吗

这就是我目前得到的(我有类似的data2和data3代码块,但为了简洁起见没有包括在内):

data1 = open("data1.txt", "r")
data2 = open("data2.txt", "r")
data3 = open("data3.txt", "r")

names = []
phones = []
socials = []
incomes = []

for line in data1: 
    if "," in line:
        parts = line.split(",")
        name = parts[0]
        if name in names:
            names = names
        else:
            name = name.strip()
            names.append(name)
        phone = parts[1]
        phone = phone.strip()
        phones.append(phone)

Tags: 文件nameintxt列表nameslinephone
1条回答
网友
1楼 · 发布于 2024-03-29 10:01:25

下面是一个如何解决这个问题的例子。这个例子既没有性能,也没有可伸缩性,因为它不使用任何索引进行查找,它只是遍历所有条目以找到一个匹配的条目。你知道吗

如果您想执行这个“过程”,我建议您考虑使用数据库。你知道吗

# A method for loading the file, which accepts a list of "headers" (or keys) 
# to be used in order to understand what data is in each file. 
# It collects all the data in the entries.
def load_file(entries, filename, keys):
    with open(filename, "r") as file:
        for line in file:
            # clean up and split by comma
            values = line.strip().split(',')
            # transform values into [("name", "a name"), ("phone", "11111111")]
            pairs = zip(keys, values)
            # transform pairs into {"name": "a name", "phone": "11111111"}
            entry = dict(pairs)
            update_or_insert(entries, entry)

def update_or_insert(entries, new_entry):
    # go through all entries
    for index, entry in enumerate(entries):
        # we need to check for matching values of each key of new_entry
        # so iterate through the items of new_entry
        for key, value in new_entry.items():
            # if a key of new_entry exists in an already existing entry
            # and their values are equal
            if key in entry and entry[key] == value:
                # merge entry and new_entry
                new_entry = {**entry, **new_entry}
                # update entry with the new merged one
                entries[index] = new_entry
                # exit the search
                return
    # if no matching values for new_entry keys were found,
    # then insert new_entry into entries
    entries.append(new_entry)

def retrieve(entries, key, value):
    for entry in entries:
        if key in entry and entry[key] == value:
            return entry

entries = []
load_file(entries, "data1.txt", ["name", "phone"])
load_file(entries, "data2.txt", ["name", "social"])
load_file(entries, "data3.txt", ["social", "income"])

print(entries)
print(retrieve(entries, "income", "2000"))
print(retrieve(entries, "name", "a name"))
print(retrieve(entries, "social", "non existent"))

相关问题 更多 >