关于将文本文件中的值组合到单个变量并打印它的问题。
我可以给出的一个例子是.txt文件,例如:
School, 234
School, 543
我想知道将两所学校合并为一个变量“学校”的必要步骤,其值为777.
我知道我们需要打开.txt文件进行读取,然后用.split(“,”)方法拆分它。
代码示例:
schoolPopulation = open("SchoolPopulation.txt", "r")
for line in schoolPopulation:
line = line.split(",")
有人可以告诉我如何解决这个问题吗?
答案 0 :(得分:1)
Python拥有丰富的标准库,您可以在其中找到许多典型任务的类。 Counter是您目前所需要的:
from collections import Counter
c = Counter()
with open('SchoolPopulation.txt', 'r') as fh:
for line in fh:
name, val = line.split(',')
c[name] += int(val)
print(c)
答案 1 :(得分:0)
这样的东西?
schoolPopulation = open("SchoolPopulation.txt", "r")
results = {}
for line in schoolPopulation:
parts = line.split(",")
name = parts[0].lower()
val = int(parts[1])
if name in results:
results[name] += val
else:
results[name] = val
print(results)
schoolPopulation.close()
您还可以使用defaultdict
和with
关键字。
from collections import defaultdict
with open("SchoolPopulation.txt", "r") as schoolPopulation:
results = defaultdict(int)
for line in schoolPopulation:
parts = line.split(",")
name = parts[0].lower()
val = int(parts[1])
results[name] += val
print(results)
如果您想要很好地显示结果,可以执行类似
的操作for key in results:
print("%s: %d" % (key, results[key]))
答案 2 :(得分:0)
school = population = prev = ''
pop_count = 0
with open('SchoolPopulation.txt', 'r') as infile:
for line in infile:
line = line.split(',')
school = line[0]
population = int(line[1])
if school == prev or prev == '':
pop_count += line[1]
else:
pass #do something else here
prev = school