[英]Correctly output dictionary to a file (fimi format) python
I have a text file containing string values separated by space " ". 我有一个文本文件,其中包含用空格“”分隔的字符串值。 I need to set each of those string values to be equal to a some number.
我需要将每个字符串值设置为等于某个数字。 So far I have done a reading from the file to a dictionary where each unique key corresponds to a value number.
到目前为止,我已经完成了从文件到字典的读取,字典中的每个唯一键都对应一个值。
import collections
with open('test.txt', 'r') as f:
c = collections.Counter(f.read().split())
newvalue = 0
for key, value in c.iteritems():
newvalue +=1
c[key] = newvalue
print key, newvalue
My problem is now that I don't know how to write the output in another file, keeping this structure: 我的问题是,现在我不知道如何将输出写到另一个文件中,保持这种结构:
my text file: 我的文字档:
desired output file: 所需的输出文件:
Can someone please help me? 有人可以帮帮我吗?
A few problems: 一些问题:
Counter
objects do not have an iteritems
method. Counter
对象没有iteritems
方法。 Here is a working sample that does what you want. 这是一个可以满足您需求的工作示例。 The biggest change is to preserve the layout of the input file by using nested lists.
最大的变化是通过使用嵌套列表来保留输入文件的布局。
import collections
with open('test.txt', 'r') as f: # open the file
lines = [] # initialize a list
for line in f: # for each line in the file,
# add a list of that line's words to the initialized list
lines.append(line.split())
# save a Counter out of the concatenation of those nested lists
c = collections.Counter(sum(lines, []))
with open('testout.txt', 'w') as output: # start a file
for line in lines: # for each list in the list we made,
result = [] # initialize a list
for word in line: # for each word in the nested list,
# add that word's count to the initialized list
result.append(str(c[word]))
# write a string representation of the list to the file
output.write(' '.join(result) + '\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.