我有一个我想在循环中运行的文件。我的文件看起来像这样:
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
我只通过Bye运行一个循环到空行。
它应该返回:
{(A, C, D, B): 2, (C, D, A, b):1, (D, C, A, B):1}
有没有办法可以调用'all'来添加所有的排列?
我想在不使用任何导入的情况下执行此操作。
到目前为止,我的功能看起来像这样:
# 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
答案 0 :(得分: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
答案 1 :(得分: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}
答案 2 :(得分: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