使用字典替换文本文件中的单词 [英] Replacing words in text file using a dictionary

查看:80
本文介绍了使用字典替换文本文件中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打开一个文本文件,然后通读它,用存储在字典中的字符串替换某些字符串.

I'm trying to open a text file and then read through it replacing certain strings with strings stored in a dictionary.

基于对>我如何编辑文本文件的答案在Python中?在进行替换之前,我可以拔出字典值,但是循环遍历字典似乎更有效.

Based on answers to How do I edit a text file in Python? I could pull out the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.

该代码不会产生任何错误,但也不会进行任何替换.

The code doesn't produce any errors, but also doesn't do any replacing.

import fileinput

text = "sample file.txt"
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}

for line in fileinput.input(text, inplace=True):
    line = line.rstrip()
    for i in fields:
         for field in fields:
             field_value = fields[field]

             if field in line:
                  line = line.replace(field, field_value)


             print line

推荐答案

我使用了我用continue跳过空白行,并用rstrip()

I skip the blank lines with continue and clean the others with rstrip()

我用fields字典中的values替换了line中找到的所有keys,并用print编写了每一行.

I replace every keys found in the line by the values in your fields dict, and I write every lines with print.

import fileinput

text = "sample file.txt"
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}


for line in fileinput.input(text, inplace=True):
    line = line.rstrip()
    if not line:
        continue
    for f_key, f_value in fields.items():
        if f_key in line:
            line = line.replace(f_key, f_value)
    print line

这篇关于使用字典替换文本文件中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆