Con*_*ett 0 python file-io dictionary file python-3.x
由于某种原因,我的代码拒绝转换为大写,我无法弄清楚为什么.我试图将字典写入一个文件,其中大写字典值被输入到一种模板文件中.
#!/usr/bin/env python3
import fileinput
from collections import Counter
#take every word from a file and put into dictionary
newDict = {}
dict2 = {}
with open('words.txt', 'r') as f:
for line in f:
k,v = line.strip().split(' ')
newDict[k.strip()] = v.strip()
print(newDict)
choice = input('Enter 1 for all uppercase keys or 2 for all lowercase, 3 for capitalized case or 0 for unchanged \n')
print("Your choice was " + choice)
if choice == 1:
for k,v in newDict.items():
newDict.update({k.upper(): v.upper()})
if choice == 2:
for k,v in newDict.items():
dict2.update({k.lower(): v})
#find keys and replace with word
print(newDict)
with open("tester.txt", "rt") as fin:
with open("outwords.txt", "wt") as fout:
for line in fin:
fout.write(line.replace('{PETNAME}', str(newDict['PETNAME:'])))
fout.write(line.replace('{ACTIVITY}', str(newDict['ACTIVITY:'])))
myfile = open("outwords.txt")
txt = myfile.read()
print(txt)
myfile.close()
Run Code Online (Sandbox Code Playgroud)
在python 3中你不能这样做:
for k,v in newDict.items():
newDict.update({k.upper(): v.upper()})
Run Code Online (Sandbox Code Playgroud)
因为它在迭代它时更改字典而python不允许(不使用python 2因为items()返回元素的副本).此外,即使它工作,它将保留旧密钥(同样:在每次迭代时创建字典非常慢......)
相反,在词典理解中重建你的词典:
newDict = {k.upper():v.upper() for k,v in newDict.items()}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1335 次 |
| 最近记录: |