首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从python中的文件进行计算

从python中的文件进行计算
EN

Stack Overflow用户
提问于 2022-11-14 15:00:56
回答 2查看 43关注 0票数 0

我有一份文件,里面有学校代码和对不同城市的投票。

该文件如下:

代码语言:javascript
复制
City: California
ADS, 532
SJD, 221
WPE, 239
City: Chicago
ADS, 238
SJD, 233
WPE, 456
...

我的问题是

  1. 如何向文件中添加信息?比方说,我想把DJF加到芝加哥,我该怎么做呢?

  1. 如何计算每个学校代码的总票数?芝加哥和加州的WPE?

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

我是个初学者,所以我仍有很多事情要处理。

EN

回答 2

Stack Overflow用户

发布于 2022-11-14 15:36:05

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

代码语言:javascript
复制
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)

希望这能有所帮助!

票数 0
EN

Stack Overflow用户

发布于 2022-11-14 16:00:49

代码语言:javascript
复制
# 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')

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74433684

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档