有很多非常强大的库可以帮助你快速完成工作,但你提到你才刚刚开始,所以我建议坚持只使用 python 本身作为学习体验。
Excel 可以将文件保存为“CSV”,这是一种非常简单的文本文件格式。 CSV 文件通常只是电子表格中每一行的逐行表示,列用逗号分隔。您的问题的一个非常简单的解决方案可能是逐行读取此类文件,确定销售数量是大于还是小于给定数量,然后将一个添加到适当的组中。
从读取文件开始非常简单。在代码中读取文件与您可能习惯的有点不同,但它非常简单,并且在不同的编程语言之间几乎总是相同的。首先,您“打开”该文件,该文件基本上要求操作系统进行访问。操作系统将确定您是否应该有权访问,如果有,将允许您访问相当于可以扫描文件的游标。这个“光标”通常被称为“文件句柄”,或者在 python 中简称为“文件对象”。
file_obj = open("data.csv", "r") #"r" for reading mode (instead of write)
一旦我们有了句柄,我们就可以调用它的read 方法来读取部分或全部文件。传递一个数字会告诉你要读取多少个字符(一个新行和一些其他不可见的代码算作一个字符),或者在 python 中你可以不传递任何参数,它将读取整个文件。因为我们以文本模式(默认)打开文件,所以我们会得到一个常规字符串。
file_contents = file_obj.read()
现在我们已经将文件的内容复制到一个字符串中,我们可以关闭文件并告诉操作系统我们已经完成了它。
file_obj.close()
您可能经常在 python 中看到这一点有点不同,使用 with 上下文以便稍微清理代码,并确保文件始终关闭:
with open("data.csv", "r") as file_obj:
file_contents = file_obj.read()
现在您有了一个包含整个 CSV 文件的大长字符串。我们希望能够逐行进行,因此我们必须在找到换行符的任何地方将字符串分成几部分。 Python 字符串使用str.split 方法可以方便地执行此操作:
file_lines = file_contents.split("\n") #split the string into a list of strings by splitting on \n chars
现在,我们将使用此列表创建一个循环来读取每一行,并确定产品的销售额是多于还是少于 200,000,000。为此,我们必须找到每一行的适当部分,将其转换为数字,并使用if 语句来决定如何处理它。最简单的 python 循环形式是遍历一个简单的项目列表中的每个项目:for line in file_lines:。现在,在循环内的每次迭代中,line 变量将填充文件该行中的任何内容。只要 csv 文件没有空行,也没有标题,我们几乎只需要找到第二个值(用逗号分隔),并将其转换为数字。这里我们将再次使用str.split 方法,在逗号处分割字符串,并将第二项转换为整数(记住python使用基于0的索引,所以第二项将是索引1)。从这里我们可以添加一些逻辑来确定我们是否应该将一个计算为低于或超过 2 亿。
over = 0
under = 0
for line in file_lines:
line_items = line.split(",")
sales = int(line_items[1])
if sales > 200000000:
over = over + 1
else:
under = under + 1
在阅读了您关于需要更多“桶”的评论后,终于有了一个更高级的版本
buckets = [0] * 8 #list of 8 buckets each starting at 0
bucket_edges = [0, 1e6, 2e6, 5e6, 1e7, 2e7, 5e7, 1e8, 2e8] #an even more advanced version would find the max and min of the sales figures, and dynamically calculate the bucket edges
with open("data.csv") as f: #"r" mode is actually the default
sales = [] #an empty list
for line in f: #a default behavior of file handles is to read line-by-line in for loops
line = line.strip() #remove leading and trailing whitespace
if not line: #an empty string will act like "False"
continue #advance to the next loop iteration
sales.append(int(line.split(",")[1])) #combine a few operations in a single line, and build up a list of sales figures
for sale in sales:
for i in range(len(buckets)):
if bucket_edges[i] <= sale < bucket_edges[i+1]:
buckets[i] += 1
for i in range(len(buckets)):
print(bucket_edges[i], "to", bucket_edges[i+1], ":", buckets[i])