我有这段代码:
import csv
import collections
def do_work():
(data,counter)=get_file('thefile.csv')
b=samples_subset1(data, counter,'/pythonwork/samples_subset3.csv',500)
return
def get_file(start_file):
with open(start_file, 'rb') as f:
data = list(csv.reader(f))
counter = collections.defaultdict(int)
for row in data:
counter[row[10]] += 1
return (data,counter)
def samples_subset1(data,counter,output_file,sample_cutoff):
with open(output_file, 'wb') as outfile:
writer = csv.writer(outfile)
b_counter=0
b=[]
for row in data:
if counter[row[10]] >= sample_cutoff:
b.append(row)
writer.writerow(row)
b_counter+=1
return (b)
我最近开始学习python,并希望从良好的习惯开始。因此,我想知道您是否可以帮助我开始将此代码转换为类。我不知道从哪里开始。
答案 0 :(得分:4)
根据我对原帖的评论,我认为这里不需要上课。但是,如果其他Python程序员读过这篇文章,我建议将它与Python样式指南PEP8内联。这是一个快速重写:
import csv
import collections
def do_work():
data, counter = get_file('thefile.csv')
b = samples_subset1(data, counter, '/pythonwork/samples_subset3.csv', 500)
def get_file(start_file):
with open(start_file, 'rb') as f:
counter = collections.defaultdict(int)
data = list(csv.reader(f))
for row in data:
counter[row[10]] += 1
return (data, counter)
def samples_subset1(data, counter, output_file, sample_cutoff):
with open(output_file, 'wb') as outfile:
writer = csv.writer(outfile)
b = []
for row in data:
if counter[row[10]] >= sample_cutoff:
b.append(row)
writer.writerow(row)
return b
注意:
None
data
,但你可以重写在你使用data
的所有地方使用迭代器,这是一个列表。答案 1 :(得分:2)
好吧,我不确定你想成为一个班级。你知道上课是什么吗?您想创建一个类来表示某种类型的 thing 。如果我正确理解您的代码,您希望过滤CSV以仅显示row[ 10 ]
至少sample_cutoff
个其他行共享的行。当然,使用Excel过滤器可以比在Python中读取文件更容易吗?
另一个帖子中的人提出的是真的,但并不适用于你的情况。你不必要地使用了很多全局变量:如果它们对代码是必要的,你应该把所有东西放到一个类中并使它们成为属性,但是因为你首先不需要它们,所以没有必要制作一个类。
有关您的代码的一些提示:
不要将文件转换为列表。这使得Python一次性将所有内容读入内存,如果你有一个大文件,那就太糟糕了。相反,只需遍历文件本身:for row in csv.reader(f):
然后,当您想第二次浏览文件时,只需执行f.seek(0)
返回顶部并重新开始。
不要将return
放在每个函数的末尾;那是不必要的。您也不需要括号:return spam
没问题。
import csv
import collections
def do_work():
with open( 'thefile.csv' ) as f:
# Open the file and count the rows.
data, counter = get_file(f)
# Go back to the start of the file.
f.seek(0)
# Filter to only common rows.
b = samples_subset1(data, counter,
'/pythonwork/samples_subset3.csv', 500)
return b
def get_file(f):
counter = collections.defaultdict(int)
data = csv.reader(f)
for row in data:
counter[row[10]] += 1
return data, counter
def samples_subset1(data, counter, output_file, sample_cutoff):
with open(output_file, 'wb') as outfile:
writer = csv.writer(outfile)
b = []
for row in data:
if counter[row[10]] >= sample_cutoff:
b.append(row)
writer.writerow(row)
return b