基本上希望从csv文件中提取值,并创建一个全局字典,我可以继续将其用于其他功能。
我不知道我是否在创建类时使用了正确的方法,所以请多多包涵。
def spread_parse但是在运行该函数时会从csv文件中提取我想要的值。我的字典“ pick”返回空白。 我知道这种方法行得通,因为如果我仅将函数“ def spread_parse”和函数“ def write”组合到一个函数中,它将创建一个具有所需值的单独文件。问题是我想使用“选择”字典中包含的新添加的值以及单个函数来创建其他函数,这些值将仅限于该函数。如果我不正确,请纠正我。
import csv
class Parse:
def __init__(self, filename):
self.filename = filename
self.picks = {}
def spread_parse(self):
"""Parses csv file"""
f = open(self.filename)
csv_f = csv.reader(f)
a = []
b = []
# Add players names to players
for row in csv_f:
a.append(row[2])
# Have to repull csv file to add prices
f = open(self.filename)
csv_f = csv.reader(f)
# Add prices of each player
for row in csv_f:
b.append(row[5])
# Copy a & b lists into players and prices to remove Players,
# Names columns
players = a[1:]
prices = b[1:]
self.picks = dict(zip(players, prices))
def write(self):
# create a file name based on week
file = 'PGA_Picks23.txt'
with open(file, 'w') as f:
for key, value in self.picks.items():
picky = (key, value)
f.writelines("\n" + str(picky))
然后我继续在单独的文件中运行该类。
import Eh as e
e.Parse('DKSal.csv').spread_parse()
e.Parse('DKSal.csv').write()
当我同时运行这两个函数时,它只会返回一个空白文件。
答案 0 :(得分:1)
您正在创建两个单独的对象。您需要创建一个Parse对象,并从中调用这两种方法:
import Eh as e
parse = e.Parse('DKSal.csv')
parse.spread_parse()
parse.write()
答案 1 :(得分:0)
除非有特定原因导致您不想使用pandas,否则我建议您这样做。熊猫有各种各样的输入和输出工具。通常,人们将数据读入DataFrame,就像一个具有行和列的电子表格一样。任何行或任何列本身都称为Series。
您可以使用var httpReq = require('../utils/http_requests');
module.exports.authenticate = function(params){
return new Promise(function(resolve, reject) {
httpReq.callToAPI(params, {
path: '/v1/authenticate',
method: 'POST'
})
.then(function(authorization) {
resolve(JSON.parse(authorization));
})
.catch(function(err) {
reject(err);
});
});
};
module.exports.currentUser = function(shaCode){
return JSON.parse(Buffer.from(shaCode.split('.')[1], 'base64').toString());
};
方法从数据框创建字典。该代码可能类似于以下内容:
var http = require('http');
function createOptions(options) {
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Connection': 'close'
};
if (options.jwt) { headers['Authorization'] = 'Bearer ' + options.jwt; }
return {
hostname: 'the.api.com',
port: 8080,
path: options.path,
method: options.method,
headers: headers
};
};
module.exports.callToAPI = function(params, options) {
reqObj = createOptions(options);
return new Promise(function(resolve, reject) {
body = [];
req = http.request(reqObj, function(res) {
res.on('data', function(chunk) {
body.push(chunk);
});
res.on('end', function() {
console.log(body.join(''));
resolve(body.join(''));
});
});
req.on('error', function(err) {
reject({ msg: "We're sorry, but something went wrong" });
});
if (params) { req.write(JSON.stringify(params)); }
req.end();
});
};