简体   繁体   English

从长文本文件中的字符串数组中查找对应的数字

[英]Find a corresponding number from an array of strings in a long text file

I have a text file that that has a single string formatted like this, each number nad name is unique:我有一个文本文件,它有一个像这样格式化的字符串,每个数字和名称都是唯一的:

{"5-6 digit number":"name", "5-6 digit number":"name", ..., "5-6 digit number":"name"} {"5-6 位号码":"姓名", "5-6 位号码":"姓名", ..., "5-6 位号码":"姓名"}

I also have a Python array that contains 200 unique name strings and I want to iterate through this array to find the matching 5-6 digit number and store it as a tuple.我还有一个包含 200 个唯一名称字符串的 Python 数组,我想遍历该数组以找到匹配的 5-6 位数字并将其存储为元组。 The problem is im unsure of what is an appropriate method to do this since the single string in the text file has the "5-6 digit number":"name" bit 24,000 times.问题是我不确定什么是合适的方法来执行此操作,因为文本文件中的单个字符串具有“5-6 位数字”:“名称”位 24,000 次。 Would it be appropriate to read in the text file and store each element as an array and search through it or use something like SQL or maybe a different approach.是否适合读入文本文件并将每个元素存储为数组并通过它进行搜索,或者使用 SQL 之类的东西,或者可能是不同的方法。

Here's an example to illustrate:这里有一个例子来说明:

Text File:文本文件:

{"774774":"John","775005":"Steve","35942":"Jacob", ...,"768252":"Matt"} (24,000 elements) {"774774":"John","775005":"Steve","35942":"Jacob", ...,"768252":"Matt"}(24,000 个元素)

Python Array: Python 阵列:

['Jacob', 'Janet', ...,'John'] (200 elements) ['Jacob', 'Janet', ...,'John'](200 个元素)

It sounds like you need an inverse mapping of name to number.听起来您需要名称到数字的逆映射。 You can use a dict comprehension for this, and just flip the key: value syntax as below:您可以为此使用dict理解,只需翻转key: value语法,如下所示:

num_to_name = {"774774":"John","775005":"Steve","35942":"Jacob", "768252":"Matt"}

name_to_num = {v: k for k, v in num_to_name.items()}

print(name_to_num)
# {'John': '774774', 'Steve': '775005', 'Jacob': '35942', 'Matt': '768252'}

Once you have a mapping of name to number, you can simply use key lookup to find the 6-digit number for each name in a list of names:一旦你有了名字到数字的映射,你可以简单地使用键查找来为名字列表中的每个名字找到 6 位数字:

array = ['Jacob', 'Janet', 'John']

for name in array:
    print(name, name_to_num.get(name, -1))  # where -1 when no number exists for name

Out:出去:

Jacob 35942
Janet -1
John 774774

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

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