2013-02-26 1075 views
2

我有一个包含类似于此生领域的最新.csv文件:只打印在.csv文件中的某些行

John,Smith,34 La La Lane,14/03/85,[email protected] 
Sarah,Second,42 Wallaby Way,11/06/92,[email protected] 
Third,Example,99 Peacock Terrace,04/12/89,[email protected] 

我想打一个程序,只打印文件中的行在某个月份出生的参赛作品(在这种情况下,该月份是在第一个斜杠之后,即dd/mm/yy)。

因此,如果需要的月份是3月份,它会打印John Smith的条目。

任何帮助将是巨大的,我一直在挣扎了一会儿

+1

请编辑您的帖子以包含您的解决方案。谢谢。 – bernie 2013-02-26 23:26:35

回答

7

我不知道你在挣扎的问题的哪一部分,所以我会给出一个有点笼统的回答。 Python有您可以使用这样一个CSV阅读:

import csv 
desiredMonth = 3 
with open('people.csv', 'rb') as csvfile: 
    content = csv.reader(csvfile, delimiter=',') 
    for row in content: 
     month = int(row[3].split('/')[1]) 
     if month == desiredMonth: 
      # print the row or store it in a list for later printing 

row就已经被分离出来,你到一个列表,所以row[3]将是生日。 split()然后将月份分成小块,[1]给出第二块,即月份。将它转换为int是个不错的主意,因此您可以轻松地将其与任何您想要的月份进行比较。

+1

我的主要问题是分裂月份。你能否进一步解释那部分代码? 感谢您的帮助! – TheFrostGuru 2013-02-26 23:35:24

+0

编辑给予更多的细节 – goron 2013-02-26 23:41:24

+0

完美!非常感谢你:) – TheFrostGuru 2013-02-26 23:44:58

1
import csv 
with open('yourfile.csv', 'rb') as csvfile: 
    spamreader = csv.reader(csvfile, delimiter=',') 
    for row in spamreader: 
     date = row[3] 
     month = date.split('/')[1] 
     if int(month) >= YOUR_MONTH_HERE 
      print row 
1

多达教程类型,因为我可以把它付诸表决:-)

somecsvfile=r'/home/me/Desktop/txt.csv' 
the_month_you_are_looking_for = 6 # as in june. 
with open(somecsvfile, 'r') as fi: 
    for line in fi: 
     list_from_text = line.split(',') 
     bday = list_from_text[3] 
     bmonth = int(bday.split('/')[1]) 
     if bmonth == the_month_you_are_looking_for: 
      print (line) 
+0

除了一堆错误之外,这不会为goron的回答添加任何内容(例如,'for line in fi.readlines():'而不是'in line in fi:',打开文件'r'而不是''rb''等)并尝试执行手动CSV解析,而不是使用'csv'。 – abarnert 2013-02-26 23:54:42

2

这里有一个不同的方法......对于CSV文件时,Python包csvkit安装了大量的命令 - 这些工具可让您轻松切割和切割.csv文件。

$ pip install csvkit 

这将安装一个名为csvgrep(等)的命令。

$ csvgrep -c 4 -r '\d{2}/03' yourfile.csv 
First,Last,Address,Birthdate,Email 
John,Smith,34 La La Lane,14/03/85,[email protected] 

有一点要注意的是,csvkit假定所有的.csv文件有标题行。这就是为什么csvgrep的结果显示标题行。这也意味着,你将有一个头添加到你这样的数据文件:

First,Last,Address,Birthdate,Email 
John,Smith,34 La La Lane,14/03/85,[email protected] 
Sarah,Second,42 Wallaby Way,11/06/92,[email protected] 
Third,Example,99 Peacock Terrace,04/12/89,[email protected] 

命令行参数的说明:

$ csvgrep -c 4 -r '\d{2}/03' yourfile.csv 
-c specifies which column you want to search 
-r specifies the regular expression you want to match in the column 

正则表达式“^ \ d {2}/03 '将匹配以2位开头的字符串,然后是'/',然后是'03'月份。

查看csvkit tutorial了解更多信息。