【问题标题】:Search the second file from the first and output to third file in python在python中从第一个文件中搜索第二个文件并输出到第三个文件
【发布时间】:2014-09-17 22:30:56
【问题描述】:

我想通过使用第一个文件作为输入并输出到第三个文件来搜索第二个文件中出现的行。它也必须很快列表是第二个文件高于 200k,第一个文件高于 75k。

**FILE 1**
1234
2324
534
235
1
643

**FILE 2**

643, 30, , , People, email@example.com,.....
1234, 45, , , People, email@example.com,.....
643, 32, , , People, email@example.com,.....
4536, 654, , , People, email@example.com,.....
898, 354, , , People, email@example.com,.....

**FILE 3**
643, 30, , , People, email@example.com,.....
1234, 45, , , People, email@example.com,.....

就是这样,伙计们。提前致谢。

【问题讨论】:

  • 你有什么代码可以分享给我们吗?
  • 我没有任何代码要分享。我对 python 不太擅长
  • SO 不适合发布此类问题。它旨在成为询问有关编程的特定问题的地方,而不是为您编写代码。尽管 Celeo 已为您发布了答案,但您不应期望每次都会发生这种情况,并且应避免提出仅描述您想要的脚本或程序的一组要求的“问题”。
  • 可以了,我又试了一次,还可以

标签: python search


【解决方案1】:

从第一个文件中读取 ids,然后使用第二个文件的行来检查起始编号是否在您收集的 ids 列表中。将匹配项添加到列表并将列表写入第三个文件。

ids = []
with open('file1') as f:
    ids.extend(id.strip() for id in f)
matches = []
with open('file2') as f:
    for line in f:
        if line.split(',')[0] in ids:
            matches.append(line)
with open('file3', 'w') as f:
    for match in matches:
        f.write(match)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 2021-12-11
    • 2016-02-05
    • 1970-01-01
    • 2014-05-01
    相关资源
    最近更新 更多