由于某种原因,我的代码拒绝转换为大写,我不明白为什么。然后我尝试将字典写入一个文件,并将大写字典值输入到某种模板文件中。
#!/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()
在 python 3 中你不能这样做:
for k,v in newDict.items():
newDict.update({k.upper(): v.upper()})
因为它在迭代时更改字典,而 python 不允许这样做(Python 2 不会发生这种情况,因为
items()
用于返回元素的 copy 作为 list
)。此外,即使它有效,它也会保留旧密钥(另外:在每次迭代时创建字典非常慢......)
相反,用字典理解重建你的字典:
newDict = {k.upper():v.upper() for k,v in newDict.items()}
请注意,它并不等同于 python 3 可以完成的操作,因为重建字典会丢失原始的小写键。要同时保留两者,有 2 个选项:
迭代项目的副本:
for k,v in tuple(newDict.items()):
newDict.update({k.upper(): v.upper()})
或者创建新词典并用它更新原始词典。
newDict.update({k.upper():v.upper() for k,v in newDict.items()})
由于参数是在调用update
之前评估的,所以不存在冲突的风险。