繁体   English   中英

如何查询我已输入的csv文件的特定列并使用python打印所有返回的行?

[英]How can i query a specific column of a csv file that i have input and print all returned rows using python?

因此,逐步引导您,这就是我要做的

1)我想将脚本放置在要分析的csv文件夹中

2)运行脚本

3)输入我要分析的.csv名称

4)输入要搜索的单词和短语,以逗号分隔

5)搜索并打印包含我指定的任何单词/短语的行

好,这是我的代码

import csv


opening_text = "Make sure this script is in the same folder as file you want to analyze \n"
print opening_text

file_name = raw_input('Enter file name ending with .csv to analyze (e.g. file.csv): ')


print "\n The file that will be analyzed is " + file_name + "\n"

my_terms = raw_input('Please enter the words and phrases you would like to find in ' + file_name + ', separated by a comma:')


single_terms= my_terms.split(',')
with open(file_name, 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in spamreader:
        for term in single_terms:
            if term in row:
                print ' '.join(row)

我当前的脚本存在以下问题:

1)它不是在搜索短语。 它可以分别搜索“嘿”和“那里”,但不能搜索“那里”

2)它没有清理我的输入。 例如,我用逗号后跟空格来划定我的字词,但是如果我要搜索的下一个短语是句子的开头,则它不会正确搜索它。

3)如果搜索词与文件内容的大小写不同,则会给出错误的结果

另外,有什么方法可以在csv文件中仅搜索一列? 例如,仅搜索“评论”列。

这是“ sample.csv”中包含的我的示例数据,我与脚本位于同一文件夹中。

样本数据

Date;Customer Name;Comments

2/12/2015;Eric;The apples were absolutely delicious

3/10/2015;Tasha;I enjoyed the mangoes thoroughly

4/11/2014;Walter;The mangoes were awesome

3/10/2009;Ben;Who killed the cat really

9/10/2088;Lisa;Eric recommended guavas for me

对于上述情况,您可能不需要正则表达式; 简单的字符串搜索即可。 但是,让我们看一下两个版本。

首先,您使用空格' '作为分隔符,这对于您提供的CSV数据是不正确的。 为了正确解析,您想使用';' 作为分隔符。 在您的示例案例中,quotechar没有任何作用,因此您可以忽略它或将其设置为常见的东西。

对于以下两个版本,我都使用以下内容:

file = 'sampledata/test.csv' # Target CSV file path
terms = 'enjoy, apples, the mangoes' # You want to replace this with your input

版本1:字符串搜索

lookup = [i.strip().lower() for i in terms.split(',')]
with open(file, 'r') as csvin:
    rdr = csv.reader(csvin, delimiter=';', quotechar='"')
    header = rdr.next()
    for row in rdr:
        for l in lookup:
            if row[header.index('Comments')].lower().find(l) != -1:
                print(row)

为了帮助您完成此过程,以下是基本步骤:

  1. 将输入terms转换为可用的项。 正如您在代码中所写的那样,我将其以逗号分隔。 另外,请strip()空格,因为它们会阻止您在注释的开头找到某些内容。

  2. 读取文件,设置CSV阅读器并从第一行绘制标题。

  3. 对于查询列表中的每一行和每个元素,我们测试查询是否存在于字符串中。 我使用lower()忽略大小写,尤其是在注释开头。

我示例性选择的输入项的结果是:

['2/12/2015', 'Eric', 'The apples were absolutely delicious']
['3/10/2015', 'Tasha', 'I enjoyed the mangoes thoroughly']
['3/10/2015', 'Tasha', 'I enjoyed the mangoes thoroughly']
['4/11/2014', 'Walter', 'The mangoes were awesome']

注意:一个注释将返回两次,因为在文本中找到了我们的两个查找元素。 您不能直接避免这种情况,但是可以事后处理。

版本2:正则表达式

上面的大多数示例都相同。 这是代码:

lookup = [re.compile(i.strip().lower()) for i in terms.split(',')]
with open(file, 'r') as csvin:
    rdr = csv.reader(csvin, delimiter=';', quotechar='"')
    header = rdr.next()
    for row in rdr:
        for l in lookup:
            m = l.search(row[header.index('Comments')].lower())
            if m is not None:
                print(row)

区别在于步骤1和3:

  1. 对于每个输入项,我们编译一个正则表达式并将其存储在我们的查找列表中。 注意:在我的示例术语中,由于不使用特殊的正则表达式运算符,因此正则表达式可以回溯到某些正则字符串搜索。 但是,您可以输入类似mango(es)?

  2. (同上)

  3. 对于每一行和每个正则表达式查找,请使用re.search()测试CSV的注释列,这将产生一个正则表达式匹配对象re.MatchObject 如果结果对象不是None ,则找到匹配项。 注意:使用匹配对象的start()方法访问找到的子字符串的位置。 有关更多功能,请参见正则表达式匹配对象上的文档。

正则表达式版本的结果与以上相同:

['2/12/2015', 'Eric', 'The apples were absolutely delicious']
['3/10/2015', 'Tasha', 'I enjoyed the mangoes thoroughly']
['3/10/2015', 'Tasha', 'I enjoyed the mangoes thoroughly']
['4/11/2014', 'Walter', 'The mangoes were awesome']

另外...

您询问是否只能搜索一列。 如果您从csv阅读器中获得一行,则它将提供由提供的定界符分割的字符串列表。 要按名称获取特定列,可以在最初绘制的标题行上使用index()函数,然后使用返回的索引访问该行列表中的元素。

暂无
暂无

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

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