【发布时间】:2020-08-29 18:02:10
【问题描述】:
不知怎的,我在 new_code 文件中没有得到任何输出。
我正在尝试读取 file.txt 并根据字典值 (find_replace_dic) 进行更改。字典的键是要被字典值替换的单词。逻辑工作正常我尝试使用 print 语句,但不知何故 new_code 文件显示空白输出。
变量“new_word”包含每个 if 和 elif 条件的新变化。
with open('file.txt','r') as file, open ('model_testing_1.txt','w') as new_code:
for line in file:
word = line.replace('\n',"").split('.')[-1]
if ':' in word:
old_model = word.strip().split(':')[-1]
old_model_s = old_model.strip()
for key in find_replace_dic:
if old_model_s == key:
new_word = line.replace(old_model_s, find_replace_dic.get(key))
print(new_word)
elif ':' not in word:
for key in find_replace_dic:
if word == key:
new_word = line.replace(word, find_replace_dic.get(key))
print(new_word)
new_code.close()
file.close()
【问题讨论】:
-
使用
with时不需要.close() -
你也可以用
if word in find_replace_dic代替整个for循环 -
@MZ 遗憾的是它仍然没有返回任何内容。
-
@MZ 添加条件是因为有些单词有'.'在它们之前,其中一些将在冒号之后被选中,而不是其他。
-
你确定它应该打印一些东西吗?你检查了吗
标签: python file dictionary replace nested