将输入列入字典

时间:2014-09-23 18:40:03

标签: python python-3.x dictionary

所以我为类设置了一个问题,我给了一个文本缩写词的csv文件,我要求提示用户输入多个缩写,如果找到缩写则应该返回全文如果没有,那么它将返回原始缩写。

我目前仍然坚持将用户输入列表正确地输入字典。

import csv

def CreateDictionary(i):            
    abbrv = i.lower()
    abbrv = i.split(' ')

    dictionary = {}
    fo = open('filename.csv')
    data = csv.reader(fo)
    for row in data:
        dictionary[row[0]] = row[1]
    fo.close()

def main():
    user = input("abbreviations")       
    print(CreateDictionary(user))

main()

4 个答案:

答案 0 :(得分:0)

import csv

def CreateDictionary(i):            
    abbrv = i.lower()
    abbrv = i.split(' ')

    dictionary = {}
    fo = open('filename.csv')
    data = csv.reader(fo)
    for row in data:
        if row[0] in abbrv: 
            yield (row[0],row[1])
    fo.close()

user = input("abbreviations")       
print(list(CreateDictionary(user)))

可能会满足您的要求

答案 1 :(得分:0)

尝试将词典中的键值添加到列表中(如果它们存在)

import csv

def CreateDictionary(i):            
    abbrv = i.lower()
    abbrv = i.split(' ')

    dictionary = {}
    fo = open('filename.csv')
    data = csv.reader(fo)
    for row in data:
        dictionary[row[0]] = row[1]
    fo.close()
    ret = []
    for i in abbrv:
        try:
            ret.append(dictionary[i])
        except KeyError:
            ret.append(i)
    return ret
def main():
    user = input("abbreviations")       
    print(CreateDictionary(user))

main()

答案 2 :(得分:0)

csv库有一个DictReader对象,可用于自动化该过程。

https://docs.python.org/3/library/csv.html#csv.DictReader

答案 3 :(得分:0)

import csv    
def CreateDictionary(i):
    abbrv = i.lower().split(' ')

    dictionary = {}
    fo = open('filename.csv')
    data = csv.reader(fo)
    for row in data:
        dictionary[row[0]] = row[1]
    fo.close()

    to_return = []
    for c in abbrv:
        to_return.append(dictionary.get(c, c))

    return ' '.join(to_return)  #if you want to return a string, if you want to
                                # return a list, use return to_return

您可以致电print CreateDictionary(i)获取您正在设计的内容。