python - 使用 Python 脚本在文件中查找和替换没有输出
问题描述
不知何故,我在 new_code 文件中没有得到任何输出。
我正在尝试读取 file.txt 并根据字典值 (find_replace_dic) 进行更改。字典的键是要被字典值替换的单词。逻辑工作正常我尝试使用打印语句但不知何故 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()
解决方案
如果我正确地关注了帖子,那么源文件中每一行的逻辑都是这样的:
- 拆分'.'上的行,获取最后一个元素
- 如果最后一个元素包含':',则进一步拆分':'上的最后一个元素,得到最后一个元素
- 如果元素在替换字典中,则从字典中替换元素
- 输出替换元素的行
此代码遵循该逻辑:
data = '''
aaa1.bb:b1.ccc1.ddd1:eee1
aaa2.bb:b2.ccc2.ddd2:eee2
aaa3.bb:b3.ccc3.ddd3:eee3
aaa1:bbb1.ccc1:ddd1.eee1
aaa2:bbb2.ccc2:ddd2.eee2
'''.strip()
with open('file.txt','w') as f: f.write(data) # test file
find_replace_dic = {'eee2':'zzz'}
################# Main Script ###################
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()
if old_model_s in find_replace_dic:
line = line[:line.rindex(':')] + ':' + find_replace_dic[old_model_s]
else: # ':' not in word
if word in find_replace_dic:
line = line[:line.rindex('.')] + '.' + find_replace_dic[word]
print (line.strip())
print (line.strip(), file=new_code)
new_code.close()
file.close()
输出
aaa1.bb:b1.ccc1.ddd1:eee1
aaa2.bb:b2.ccc2.ddd2:zzz
aaa3.bb:b3.ccc3.ddd3:eee3
aaa1:bbb1.ccc1:ddd1.eee1
aaa2:bbb2.ccc2:ddd2.zzz
推荐阅读
- c - 如何在C中按索引连接两个字符串数组索引?
- r - glm 模型对训练后添加的未知因子水平有什么作用?
- unity3d - 如何在 Unity 中将键盘控件转换为触摸屏
- angular - 如何一次只突出显示单个 mat-list 元素
- mongodb - MongoDB PHP聚合 - 输出数组中的数据集不正确
- jquery - 选择多个下拉菜单时如何启动功能
- spring-boot - 如何使用 oauth2 范围测试 Spring PreAuthorize
- angular - 加载子组件选择器时加载父组件(没有层次结构 URL)?
- javascript - Angular 7 为什么将正文转换为 JSON 字符串和对象
- javascript - 子菜单不与侧父元素重叠