我是Python的新手,但我想对一些csv文件进行一些数据分析。我想从仅包含一些关键字的csv文件中打印行。我使用第一个块来打印所有有效行。从这些行我想打印包括关键字的那些。谢谢你的帮助。
csv.field_size_limit(sys.maxsize)
invalids = 0
valids = 0
for f in ['1.csv']:
reader = csv.reader(open(f, 'rU'), delimiter='|', quotechar='\\')
for row in reader:
try:
print row[2]
valids += 1
except:
invalids += 1
print 'parsed %s records. ignored %s' % (valids, invalids)
使用关键字:
for w in ['ford', 'hyundai','honda', 'jeep', 'maserati','audi','jaguar', 'volkswagen','chevrolet','chrysler']:
我想我需要使用if语句来过滤我的顶级代码,但我一直在努力解决这个问题几个小时似乎无法让它发挥作用。
答案 0 :(得分:0)
你的猜测是正确的。您需要做的就是使用if语句过滤行,检查每个字段是否与关键字匹配。以下是您的操作方法(我还对您的代码进行了一些改进,并在评论中对其进行了解释。):
# First, create a set of the keywords. Sets are faster than a list for
# checking if they contain an element. The curly brackets create a set.
keywords = {'ford', 'hyundai','honda', 'jeep', 'maserati','audi','jaguar',
'volkswagen','chevrolet','chrysler'}
csv.field_size_limit(sys.maxsize)
invalids = 0
valids = 0
for filename in ['1.csv']:
# The with statement in Python makes sure that your file is properly closed
# (automatically) when an error occurs. This is a common idiom.
# In addition, CSV files should be opened only in 'rb' mode.
with open(filename, 'rb') as f:
reader = csv.reader(f, delimiter='|', quotechar='\\')
for row in reader:
try:
print row[2]
valids += 1
# Don't use bare except clauses. It will catch
# exceptions you don't want or intend to catch.
except IndexError:
invalids += 1
# The filtering is done here.
for field in row:
if field in keywords:
print row
break
# Prefer the str.format() method over the old style string formatting.
print 'parsed {0} records. ignored {1}'.format(valids, invalids)