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
4

3 回答 3

1
read = False    
counting_dict = {}
#run through the lines in the file
for line in file:
    if read and 'Hello' not in line:
        #do as if the entry already exists
        try:
            counting_dict[tuple(line.split())] += 1
        #if not, create it
        except KeyError:
            counting_dict[tuple(line.split())] = 1
    elif 'Bye' in line:
        read = True
    #if 'Hello' is in the line but 'Bye' is not,set read to False
    else:
        read = False
于 2012-11-30T10:01:25.283 回答
1

像这样,在 处拆分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}
于 2012-11-30T10:01:46.167 回答
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
于 2012-11-30T10:11:50.013 回答