【发布时间】:2016-03-11 21:16:12
【问题描述】:
所以要引导你完成它,这就是我想做的事情
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.DictReader,它返回字典。这样您就可以在特定列中进行搜索。在比较或查看字符串时将文本转换为小写。
-
这还不是全部,@BobEzuba。 csv 阅读器的分隔符设置不正确,比较是在集合中搜索元素,而不是在字符串中。问题已正确发布,我觉得 OP 至少花费了一些努力来解决出现的问题。