背景故事一点点:
我有一个程序,允许用户输入一个名称(如里斯本),以及基于用户输入的国家,该计划将通过我的JSON文件回路,并打印出所有有关在里斯本的国家/下降(如翡翠,约翰) 。
这是我的JSON文件:
{
"user1":{
"Country":[
"China",
"USA",
"Nepal"
],
"Name":[
"Lisbon"
]
},
"user2":{
"Country":[
"Sweden",
"China",
"USA"
],
"Name":[
"Jade"
]
},
"user3":{
"Country":[
"India",
"China",
"USA"
],
"Name":[
"John"
]
}
}
我是新来的Python,我想知道我怎么导出我的打印结果,并在同一时间格式好听到CSV文件,这是我的打印结果:
Jade : Sweden, China, USA
John : India, China, USA
这是我想它在CSV文件看:
Name Country
Jade Sweden, China, USA
John India, China, USA
这是我到目前为止已经完成:
def matchCountry():
userName = raw_input("Enter user's name: ")
with open('listOfUsers.json') as f:
data = json.load(f)
def getId(name):
for userId, v in data.items():
if v['Name'][0].lower() == name:
return userId;
id = getId(userName)
for k, v in data.items():
if any(x in data[id]['Country'] for x in v['Country']):
if v['Name'][0].lower() != userName.lower():
print (v['Name'][0] + " : " + ", ".join(v['Country']))
with open('output.csv', 'ab') as csvfile:
csvwriter = csv.writer(csvfile)
for row in result.items():
csvwriter.writerow(row)
有很多方法可以做到这一点,但你可以考虑存储在pandas dataframe的数据,然后将数据写入到.csv。
例如,
import pandas as pd
df = pd.DataFrame({'Names':['John','Jane'],
'Countries':[['Spain','India','USA'],['China','Spain','India']]})
df.to_csv('filepath_to_save',index=False)
这写道:
Countries,Names
"[Spain,India,USA]",John
"[China,Spain,India]",Jane
这样做的缺点是,因为你有多个值一列,它不会在最有吸引力的格式保存。如果你知道的人不仅会,比方说,你有没有可以做三个或更少的国家:
df = pd.DataFrame({'Names':['John','Jane'],
'Country_one':['Spain','China'],
'Country_two':['India','Spain'],
'Country_three':['USA','India']})
# save to .csv ordering the columns
df.to_csv('filepath_to_save',index=False, header=True,
columns=["Names","Country_one","Country_two","Country_three"])
其中写道:
Names,Country_one,Country_two,Country_three
John,Spain,India,USA
Jane,China,Spain,India
那么这将保存在一个漂亮的.csv格式,但多的缺点
我这样做,而不是,纠正我,如果这是不好的编码或不!
with open('output.csv', 'w') as csvfile:
csvwriter = csv.writer(csvfile, f, lineterminator='\n')
csvwriter.writerow(["Name", "Country"])
for k, v in data.items():
if any(x in data[id]['Country'] for x in v['Country']):
if v['Name'][0].lower() != userName.lower():
csvwriter.writerow([v['Name'][0], ", ".join(v['Country'])])
这是我在CSV文件输出:
Name Country
Jade Sweden, China, USA
John India, China, USA
测试的Python 3.6.7
# -*- coding: utf-8 -*-
import json
import os
def matchCountry():
userName = input("Enter user's name: ")
with open('list_of_users.json') as f:
data = json.load(f)
def getId(name):
for userId, v in data.items():
if v['Name'][0].lower() == name:
return userId;
id = getId(userName)
results = []
for k, v in data.items():
if any(x in data[id]['Country'] for x in v['Country']):
if v['Name'][0].lower() != userName.lower():
r = v['Name'][0] + "\t" + ", ".join(v['Country'])
print(r)
results.append(r)
if not os.path.exists('output.csv'):
with open('output.csv', 'w') as csvfile:
csvfile.write("Name\tCountry\n")
with open('output.csv', 'a') as csvfile:
for row in results:
csvfile.write(row + "\n")
def main():
matchCountry()
if __name__ == '__main__':
main()