我对python还不熟悉,正在尝试使用python2.7将字典值写入一个文件。我的字典D
中的值是一个至少包含2个项目的列表。在
字典的键为TERM_ID
和
值的格式为[[DOC42, POS10, POS22], [DOC32, POS45]]
。在
这意味着TERM_ID
(键)位于DOC42的POS10、POS22位置,它也位于DOC32的POS45位置
所以我必须以以下格式写入一个新文件:每个TERM_ID
都有一个新行
TERM_ID (tab) DOC42:POS10 (tab) 0:POS22 (tab) DOC32:POS45
下面的代码将帮助您理解我到底想做什么。在
^{pr2}$我得到的输出是:
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
5409:1
4 405:1455
436:1
142:145
11:1
184:1
6 13:15
417:13
8141:1
170:1
186:14
预期产量:
57 422:1
3 879:1 162:1
5409:1
4 405:1455 436:1 142:145 11:1 184:1
6 13:15 417:13
8 141:1 170:1 186:14
您可能没有得到预期的结果,因为在读取输入数据时没有去掉换行符
\n
。尝试更换与
要在输出文件中强制执行上述换行符,请添加
在第二个外部
for
循环的最后:底线:
write
从不添加换行符。如果您在输出文件中看到一个,那么它就在您的数据中。在相关问题 更多 >
编程相关推荐