Python 如何将列表从文件转换为字典

Python 如何将列表从文件转换为字典,python,list,dictionary,for-loop,Python,List,Dictionary,For Loop,我有一个文件我想在循环中运行。我的文件如下所示: Hello Hello A B C D A B C D B C D A B C D A C D A B B C D A Hello Bye A C D B C D A B A C D B D C A B 我只通过“再见”循环到空白行 它应返回: {(A, C, D, B): 2, (C, D, A, b):1, (D, C, A, B):1} 有没有一种方法我可以称之为“全部”来添加所有排列 我想在不使用任何导入的情况下执行此操作 到目前

我有一个文件我想在循环中运行。我的文件如下所示:

Hello Hello
A B C D
A B C D
B C D A
B C D A
C D A B
B C D A

Hello Bye
A C D B
C D A B
A C D B
D C A B
我只通过“再见”循环到空白行

它应返回:

 {(A, C, D, B): 2, (C, D, A, b):1, (D, C, A, B):1}
有没有一种方法我可以称之为“全部”来添加所有排列

我想在不使用任何导入的情况下执行此操作

到目前为止,我的函数如下所示:

# input_word = Hello or Bye
def file_to_dict (file, input_word):
    new_dict = {}
    new_list = []

    flag = False
    for line in f:
        if 'Hello' in line:
            continue
        if not line.strip():
            continue
        lElts = tuple(line.split(' '))
        if lElts in dRet:
            dRet[lElts] += 1
        else:
            dRet[lElts] = 1
    return dRet
是否有继续的替代方案

这给了我一个错误,说:

ValueError: I/O operation on closed file

类似这样,在
hello Bye
处拆分,然后使用
dict.get()
向字典添加值

In [17]: with open("data.txt") as f:

    spl=f.read().split("Hello Bye")

    #now spl[1] is  

    #
    #A C D B
    #C D A B
    #A C D B
    #D C A B

    #we need to now split these at '\n', or may be use `splitlines()`
    #for every line apply split, which returns ['D', 'C', 'A', 'B']
    #apply tuple() to it, to make it hashable.
    #now you can use use either defaultdict(int) or dict.get() as used below.

    dic={}                         
    for x in spl[1].split('\n'):
        if x.strip():
            key=tuple(x.split())
            dic[key]=dic.get(key,0)+1;
    print dic
   ....:     
{('D', 'C', 'A', 'B'): 1, ('A', 'C', 'D', 'B'): 2, ('C', 'D', 'A', 'B'): 1}

有很多逻辑错误。。。我建议您查看
elif
的工作原理

def f_to_dict(f):
    dRet = {}
    for line in f:
        if 'Hello' in line:
            continue
        if not line.strip():
            continue
        lElts = tuple(line.split(' '))
        if lElts in dRet:
            dRet[lElts] += 1
        else:
            dRet[lElts] = 1
    return dRet

那么它有什么问题呢?给出预期输出与实际输出,给出错误。。我似乎无法接受文件中的内容:(错误是什么?复制粘贴是您的朋友。请在提问时尽可能多地提供详细信息。另外,请格式化您的代码!在Python格式化问题中!您的意思是
IndentationError
?每当您尝试使用关闭的文件时,都会出现此错误。请确保该文件是正确打开的文件。如下所示:
file=open('file_name','r')
我不介意这个方法是否很长,但它应该更容易理解,如果你能编辑我的逻辑,那就太好了。我能问一下try是做什么的吗?它是一个独立的内置函数还是定义另一个函数的东西?
try
允许处理异常:如果你只需执行
一个dict[a_key]+=1
a_key
在字典中不存在,将引发错误
KeyError
。在上述情况下,程序在这种情况下不会停止,但执行
下除KeyError:
之外的部分,其中不存在的键被添加到字典中。如果我有新的l,我可以问我做错了什么吗那么我是不是用它来做一个口述…这行得通吗?你能更详细一点…告诉我每件事都在做什么,因为我想用代码的概念,而不是复制过去的代码:S@user1853961我已经添加了更多的细节。非常感谢!我要试试这个..除了这对我的级别有点高级给我这个错误:对于文件中的行:Valuerror:对关闭的文件执行I/O操作。首先打开该文件,它就会工作。如果您有一个名为this_is_a_file.txt的文件,请键入
file=open('this_is_a_file.txt','r')
def f_to_dict(f):
    dRet = {}
    for line in f:
        if 'Hello' in line:
            continue
        if not line.strip():
            continue
        lElts = tuple(line.split(' '))
        if lElts in dRet:
            dRet[lElts] += 1
        else:
            dRet[lElts] = 1
    return dRet