【问题标题】:How to find string matches between a text file and CSV?如何在文本文件和 CSV 之间查找字符串匹配项?
【发布时间】:2020-09-22 04:48:24
【问题描述】:

我目前正在独立系统上使用 Python 2.7。我解决这个问题的首选方法是使用 pandas 数据框进行比较。但是,我无权在我正在使用的系统上安装该库。所以我的问题是我还能如何使用文本文件并在 csv 中查找字符串的匹配项。

如果我有一个包含许多字段的主 csv 文件(为了相关性,第一个是时间戳)和其他几个包含时间戳列表的文本文件,我如何将每个 txt 文件与主 csv 进行比较,如果匹配发现根据特定字段匹配从 csv 中抓取整行并将该结果输出到另一个 csv

例子:

example.csv

timestamp,otherfield,otherfield2
1.2345,,
2.3456,,
3.4567,,
5.7867,,
8.3654,,
12.3434,,
32.4355,,

example1.txt

2.3456
3.4565

example2.txt

12.3434
32.4355

如果有任何问题,我很乐意回答。

【问题讨论】:

  • 到目前为止你尝试过什么?你有代码显示你的尝试吗?示例输出会是什么样子?

标签: python-2.7 csv string-matching


【解决方案1】:

您可以将所有文件加载到列表中,然后使用搜索列表

with open('example.txt','r') as file_handle:
    example_file_content = file_handle.read().split("\n")

with open("example1.txt", "r") as file_handle:  
    example1_file_content = file_handle.read().split("\n")

for index, line in enumerate(example_file_content):
    if line.split(",")[0] in example1_file_content:
        print('match found; line is',line)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 2021-12-15
    • 2014-04-09
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    相关资源
    最近更新 更多