如何根据用户输入创建嵌套字典,然后从csv

时间:2019-05-02 05:05:56

标签: python python-3.x dictionary nested export-to-csv

我正在尝试编写一个嵌套的字典,其中每个键是一个用户查询,每个值是一个字典,其中包含一个文件以及该文件中查询的频率。

在搜索时我发现了

import csv
import itertools

def mergedict(a,b):
    a.update(b)
    return a

fields = [ 'org', '2015', '2014', '2013' ]
dw     = { 'orgname1': { '2015' : 2, '2014' : 1, '2013' : 1 },
           'orgname2': { '2015' : 1, '2014' : 2, '2013' : 3 },
           'orgname3': { '2015' : 1, '2014' : 3, '2013' : 1 }
        }

with open("test_output.csv", "wb") as f:
    w = csv.DictWriter( f, fields )
    w.writeheader()
    for k,d in sorted(dw.items()):
        w.writerow(mergedict({'org': k},d))

我的目标是:

import csv
import itertools

def mergedict(a,b):
    a.update(b)
    return a

fields = [ 'UserInput', 'Filename1', 'Filename2', 'Filename3' ]
past_search = { 'ham': { 'alice.txt' : 21, 'moby_dick.txt' : 11, 'cat_n_hat.txt' : 1 },
           'dog': { 'alice.txt' : 25, 'moby_dick.txt' : 13, 'cat_n_hat.txt' : 8 },
           'cat': { 'alice.txt' : 5, 'moby_dick.txt' : 1, 'cat_n_hat.txt' : 1 },

with open("pastQueries.csv", "wb") as f:
    w = csv.DictWriter( f, fields )
    w.writeheader()
    for k,d in sorted(dw.items()):
        w.writerow(mergedict({'user_query': k},d))

我正在努力让字典来接受用户输入并编写阅读器功能,以便可以从csv中提取数据。我目前有这个

#Get user's search term
query = input("Please enter your query/queries separated by a comma.")

具有此功能

try:
        with open(filename, encoding='utf-8') as f_obj:
            contents = f_obj.read()
    except FileNotFoundError:
        pass
    else:
        # Count approximate number of words in the file.
        words = contents.split()
        num_words = len(words)
        for word in words:
            if query.title()==word.title():
                term_frequency+=1                
        tf = term_frequency/num_words
#add results to past query dictionary and write to csv
        pquerydict[query] = {filename : tf}
        with open('PastQueries.csv', 'w') as csv_file:
            writer = csv.writer(csv_file)
            for key, value in pquerydict.items():
                w.writerow([query] + [pquerydict[filename][tf]])

0 个答案:

没有答案