【问题标题】:Use Python to search and pull data from Excel使用 Python 从 Excel 中搜索和提取数据
【发布时间】:2016-02-08 23:34:54
【问题描述】:
import csv

subject = ['emergency*', 'new ticket*', 'problem with*']
from_to = ['chris*', 'timothy*', 'daniel*', 'david*', 'jason*']

a = open('D:\testfile.csv', 'w')

python 新手。所以,这就是我想做的事情。

1) 打开一个 excel csv 文件

2) 搜索列表中的特定关键字

3) 如果找到关键字,则仅提取 D、E、F 列中的数据。 (因为那是关键字所在的位置)

4) 将此数据写入新文件

示例。在 testfile.csv 中搜索 from_to 列表中的任何关键字。如果这些关键字仅出现在 excel 的 D 或 E 列中并且如果相应的列 F 不等于主题列表,则编写一个包含 D、E、F 列和相关行的新文件,无论那里有多少是,有它

此外,我将星号放在列表中的名称/项目旁边以表示通配符,例如,如果 from_to 包含 chris.gmail.com 或 daniel@yahoo。

【问题讨论】:

    标签: python excel csv python-3.x


    【解决方案1】:

    此解决方案有一个关键字列表,一个您逐行读取的输入文件,将每一行标记为一个字符串列表,然后迭代您的关键字列表以检查它们中的任何一个是否在标记化的行中。如果找到任何关键字,它将将该行写入输出文件。

    keywrds = ["word1", "word2", "etc"]
    with open ("myfile.csv") as fin:
        with open ("outfile.txt") as fout:
            for line in fin:
                line_tokens = line.split(",")
                for word in keywrds:
                    if word in line_tokens:
                        fout.write(line_tokens[3:6].join(" ") + "\n")
    

    【讨论】:

    • 谢谢。我使用的 * 会在列表中用作通配符吗?以及如何将外观与 and 语句结合起来以确保主题关键字列表不匹配?
    • 不,您的通配符 * 不起作用。我想不出任何简单的方法来实现它。对于额外的检查,您需要在 if 语句中添加另一个 for 循环,该循环遍历主题关键字以检查它们是否在 line_tokens 中。
    猜你喜欢
    • 2021-07-01
    • 2021-10-05
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 2021-01-12
    • 2015-02-07
    • 2016-06-06
    相关资源
    最近更新 更多