【发布时间】:2014-10-03 01:00:10
【问题描述】:
我是 python 新手,正在尝试使用 Python 2.7 将我的字典值写入文件。我的 Dictionary D 中的值是一个至少包含 2 个项目的列表。
字典的键为 TERM_ID 和
值的格式为[[DOC42, POS10, POS22], [DOC32, POS45]]。
表示TERM_ID(key)位于 DOC42 的 POS10、POS22 位置,也位于 DOC32 的 POS45
所以我必须以以下格式写入一个新文件:每个 TERM_ID 一个新行
TERM_ID (tab) DOC42:POS10 (tab) 0:POS22 (tab) DOC32:POS45
以下代码将帮助您了解究竟要做什么。
for key,valuelist in D.items():
#first value in each list is an ID
docID = valuelist[0][0]
for lst in valuelist:
file.write('\t' + lst[0] + ':' + lst[1])
lst.pop(0)
lst.pop(0)
for n in range(len(lst)):
file,write('\t0:' + lst[0])
lst.pop(0)
我得到的输出是:
TERM_ID (tab) DOC42:POS10 (tab) 0:POS22
DOC32:POS45
我尝试使用新的行标记以及逗号在同一行的任何位置继续写入文件,但它不起作用。 我无法理解文件写入的真正工作原理。
任何类型的输入都会有所帮助。谢谢!
@Falko 我找不到附加文本文件的方法,因此这是我的示例数据-
879\t3\t1
162\t3\t1
405\t4\t1455
409\t5\t1
13\t6\t15
417\t6\t13
422\t57\t1
436\t4\t1
141\t8\t1
142\t4\t145
170\t8\t1
11\t4\t1
184\t4\t1
186\t8\t14
我的示例运行代码是 -
with open('sampledata.txt','r') as sample,open('result.txt','w') as file:
d = {}
#term= ''
#docIndexLines = docIndex.readlines()
#form a d with format [[doc a, pos 1, pos 2], [doc b, poa 3, pos 8]]
for l in sample:
tID = -1
someLst = l.split('\\t')
#if len(someLst) >= 2:
tID = someLst[1]
someLst.pop(1)
#if term not in d:
if not d.has_key(tID):
d[tID] = [someLst]
else:
d[tID].append(someLst)
#read the dionary to generate result file
docID = 0
for key,valuelist in d.items():
file.write(str(key))
for lst in valuelist:
file.write('\t' + lst[0] + ':' + lst[1])
lst.pop(0)
lst.pop(0)
for n in range(len(lst)):
file.write('\t0:' + lst[0])
lst.pop(0)
我的输出:
57 422:1
3 879:1
162:1
5 409:1
4 405:1455
436:1
142:145
11:1
184:1
6 13:15
417:13
8 141:1
170:1
186:14
预期输出:
57 422:1
3 879:1 162:1
5 409:1
4 405:1455 436:1 142:145 11:1 184:1
6 13:15 417:13
8 141:1 170:1 186:14
【问题讨论】:
-
file,write(逗号)中有一个错字,但这可能不是真正的问题。包括生成一些虚拟D的最小运行示例会很有帮助。 -
@Falko 我找不到附加文件的方法,因此更新了问题以帮助您了解我的数据、代码和输出。
标签: python list python-2.7 dictionary