将字典正确输出到python文件(fimi格式)
我有一个文本文件,其中包含由空格“”分隔的字符串值。我需要将每个字符串值设置为等于某个数字。 到目前为止,我已经完成了从文件到字典的读取,其中每个唯一键对应一个值编号将字典正确输出到python文件(fimi格式),python,dictionary,Python,Dictionary,我有一个文本文件,其中包含由空格“”分隔的字符串值。我需要将每个字符串值设置为等于某个数字。 到目前为止,我已经完成了从文件到字典的读取,其中每个唯一键对应一个值编号 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
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
我现在的问题是,我不知道如何在另一个文件中写入输出,保持这种结构:
我的文本文件:
- 电脑电话图书馆书桌
- 书场弹簧电话
- 书泉
- 123445
- 5 6 7 2
- 5.7
计数器
对象没有iteritems
方法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')
文本文件的外观如何?提供一个test.txt示例。控制台上是否有所需的输出?
print
语句是否产生正确的结果?对于文件对象上的write
,替换print
?文件每行包含不同的字数。但其中一些话正在重复。我想让重复的单词保持相同的数字,并保持行相同(只是现在,单词被相应的数字替换)实际上我得到了字典:(从上面的例子中){'yard':1,'spring':2,'library':3,'phone':4,'computer':5,'book':6}键和值打印在一行上。我希望用数字值替换这些单词,但每个单词都保留在同一行上。我试图从文件中的行创建列表,但我一直在研究如何将列表值替换为字典中的值。可能吗?谢谢,这对我帮助很大。