【问题标题】:searching for strings in all lines of a text file: Python在文本文件的所有行中搜索字符串:Python
【发布时间】:2011-12-12 19:19:19
【问题描述】:

这里有问题,希望能得到一些帮助。

我有一个文本文件,每行都有一个 ID 号和一组“描述符”。描述符对于每一行可能是唯一的,也可能不是唯一的(它们可以在整个文档中多次使用)。

我基本上想识别包含某个描述符的所有 ID 号......我的代码正在工作,但它只找到描述符的第一次出现,而不是所有这些。有什么快速解决办法吗?

所有的描述符已经在一个列表中。 文本文件示例:

ID_45555 (tab) some irrelevant data (tab) **DESCRIPTOR1** DESCRIPTOR2 DESCRIPTOR3

ID_55555 (tab) some irrelevant data (tab) DESCRIPTOR200 **DESCRIPTOR1** DESCRIPTOR599

代码:

for line in file:
    line = line.strip()
    line = line.split("\t")
    IDNUMBER = line[0]
    DESCRIPTOR = line[2]
    for x in total_list:
        if x in DESCRIPTOR:
            print x, DESCRIPTOR

【问题讨论】:

    标签: python search loops


    【解决方案1】:

    我建议为此使用 dict,描述符作为键,相应的 ID 作为值。您浏览文件并在每一行将 ID 添加到字典中每个描述符下的列表中。例如:

    by_descriptors = collections.defaultdict(list)
    for line in file:
        id, _, descriptors = line.strip().split("\t")
        for d in descriptors.split():
            by_descriptors[d].append(id)
    # to find all IDs for a given descriptor:
    by_descriptors.get(id, [])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-24
      • 2013-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多