gpt4 book ai didi

python - 从基于列表字段的文件中获取行计数 python 3

转载 作者:行者123 更新时间:2023-12-01 02:16:54 28 4
gpt4 key购买 nike

我在代码中读取了一个文件,然后我从列表中的源中获取了一个年份字段,现在我需要每年遍历该文件以找出每年有多少行。

我在 Excel 中进行了练习,我期望得到以下输出:

enter image description here

我的代码:

input_f = open("C:\\Users\\P928260\\Downloads\\ssa-pop3-eng.csv","r")
next(input_f)


years_unique = []
controler = False

while(controler != True):
counter_rows = 0
#Get a list with the read years
for line in input_f:
item = line.split(',')
year_f = item[0][:4]
if (year_f not in years_unique):
years_unique.append(year_f)


input_f.close()

input_f = open("C:\\Users\\P928260\\Downloads\\ssa-pop3-eng.csv","r")
next(input_f)


for year in years_unique:
for line in input_f:
item = line.split(',')
year_f = item[0][:4]
if (year == year_f):
counter_rows +=1

print(year,counter_rows)


controler = True

我当前的输出仅打印适用于 2012 年的相同行帐户,但不包括其他年份。我知道我已经很接近了。我感谢你们的帮助。

enter image description here

最佳答案

您想要在代码中更改一些内容。

必要时使用上下文管理器。无论是否发生异常,您都可以使用它隐式管理文件关闭。

您还可以使用collections 库中的defaultdict。它有助于设置一个默认工厂,用于设置首次在字典中访问的任何键的初始值。在本例中,我们使用 int 内置函数将默认值设置为 0

from collections import defaultdict

year_count = defaultdict(int)

with open("C:\\Users\\P928260\\Downloads\\ssa-pop3-eng.csv","r") as file:
for line in file:
year, *rest = line.split(',')
year = year.strip() # clean year
year_count[year] += 1

for year, count in year_count.items():
print(year, count)

关于python - 从基于列表字段的文件中获取行计数 python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48309356/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com