在python中从文件中计算



我有一个包含不同城市的学校代码和投票的文件。

文件如下:

City: California
ADS, 532
SJD, 221
WPE, 239
City: Chicago
ADS, 238
SJD, 233
WPE, 456
...

我的问题是

  1. 如何添加信息到文件?比如说,我想加DJF,芝加哥是204,怎么做呢?

  2. 如何计算每个学校代码的总票数?比如WPE在芝加哥和加州的业务?

我试着用字典使它更容易,但我感到迷茫。此外,我还设置了代码以向文件添加新信息,但我希望将其添加到特定的类别中,而不仅仅是在文件的末尾。

注:我是初学者,所以我还有很多事情要处理。

欢迎来到SO!要实现您想要的,您基本上可以创建一个包含键和值对的嵌套字典。然后,您可以访问第一级键并在文件中添加其他信息,例如芝加哥的DJF。然后,您可以将该字典作为json对象写入文件。要得到和,你可以用求和函数。下面是代码:

import json
dictForCities ={"California" : {"ADS" : 532, "SJD": 221, "WPE" : 239 }, "Chicago": {"ADS": 238, "SJD": 233, "WPE": 456}}
dictForCities["Chicago"]["DJF"] = 204
with open('test', 'w') as f:
f.write(json.dumps(dictForCities))

# To get the total of votes 
sumForADS = sum(d['ADS'] for d in dictForCities.values() if d)
sumForWPE = sum(d['WPE'] for d in dictForCities.values() if d)
print(sumForADS)
print(sumForWPE)

希望这对你有帮助!

# start of temporary file read
data = '''City: California
ADS, 532
SJD, 221
WPE, 239
City: Chicago
ADS, 238
SJD, 233
WPE, 456'''
# change it to your file read method, e.g.:
# with open('data.txt','r') as f:
#     data = f.read()
#     ...
import tempfile
with tempfile.TemporaryFile(mode='w+') as fp:
fp.write(data)
fp.seek(0)
data = fp.read()
# end of temporary file read

lines = data.split('n')
cities = dict()
last_city = None
for line in lines: # you can use `for line in f:` if your file is big
line = line.strip() # remove leading and trailing spaces
if line.startswith('City:'): # is this line a city's name?
last_city = line.removeprefix('City: ') # then save it without the `City: ` part
elif last_city is not None: # do we have any city saved?
name, value = line.split(',') # split line into a list: `ADS, 532` -> ['ADS', ' 532'], note the extra space before 532
name = name.strip() # remove spaces
value = int(value.strip()) # remove spaces and convert to integer
values = cities.setdefault(last_city,dict()) # get the dictionary at key `last_city` or return a new one if it doesn't exist yet
values[name] = value # add value to this dictionary, this is the same as the `cities[last_city]' so it will get added here too

# now we have our data structure filled with data from the file
# function to print cities
def print_cities(cities):
for city,values in cities.items():
print(city)
for name,value in values.items():
print(f't{name}: {value}')
print('-'*16) # separator

#let's print it
print_cities(cities)
# add a new value to it
cities['Chicago']['DJF'] = 204
# let's print again, note that the DJF, 204 got added to Chicago
print_cities(cities)

# write to file
with open('output.txt','w') as f:
for city,values in cities.items():
f.write(f'City: {city}n')
for name,value in values.items():
f.write(f'{name}, {value}n')

我试图解释每一行,我还添加了一个临时文件读取,这是你不需要的,但因为我没有你的文件,也不知道它看起来是什么样子,我复制了顶部的内容,并试图模拟文件读取。您可以将该部分与我还添加的普通文件读取交换。

您需要将文件读入数据结构,修改其内容,然后将其写入文件。

相关内容

  • 没有找到相关文章

最新更新