简体   繁体   English

如何使用python脚本用字典键值替换文件中的字符串值

[英]How to Replace value of string in file with dictionary key-value using python script

How can I replace a string in file with dictionary value using python:如何使用 python 用字典值替换文件中的字符串:

I have a file with content as below:我有一个内容如下的文件:

No.of documents inserted in collection{col_id="feed-496"} 580
No.of documents inserted in collection{col_id="feed-497"} 620
No.of documents inserted in collection{col_id="feed-498"} 630

Now I have a dictionary as below:现在我有一本字典如下:

dict1={'feed-496':'high','feed-497':'low','feed-498':'medium'}

How can I replace 'feed-496' in file with key value from above dictionary using python script.如何使用 python 脚本将文件中的 'feed-496' 替换为上述字典中的键值。

Approach with built-ins:内置方法:

# file_contents = file.read() or similar, as long as it's a string.

for find, replacement in dict1.items():
    file_contents.replace(find, replacement)

Note that replacements in this case should never have also appear in the dictionary keys or they will end up being replaced by later iterations of the loop.请注意,这种情况下的替换不应该也出现在字典键中,否则它们最终将被循环的后续迭代替换。

Alternatively, with regex:或者,使用正则表达式:

import re

# ...

# Make a function that picks what to replace with.
def feed_level(match_obj):
    # Use the capture group (see regex below) as key for the dictionary.
    return dict1[match_obj.group(0)]

re.sub(r'col_id="(.*?)"', feed_level, file_contents)

This does not have the same limitation as the other approach above.这与上述其他方法没有相同的限制。 Both possibilities allow you to expand the dictionary at any time without having to modify this code when you do it.这两种可能性都允许您随时扩展字典,而无需在执行此代码时修改此代码。

To replace certain strings in a text file use .replace(wrongelement, rightelement)要替换文本文件中的某些字符串,请使用 .replace(wrongelement, rightelement)

in.txt:在.txt:

Hello and welcome to pyton.您好,欢迎来到 pyton。

Code:代码:

fin = open("in.txt", "rt")
fout = open("out.txt", "wt")

for line in fin:
    fout.write(line.replace('pyton', 'python'))

fin.close()
fout.close()

out.txt:输出.txt:

Hello and welcome to python.你好,欢迎来到 python。

Your code would then look something like this:您的代码将如下所示:

dict1={'feed-496':'high','feed-497':'low','feed-498':'medium'}
fin = open("in.txt", "rt")
fout = open("out.txt", "wt")

for line in fin:
    for key in dict1:
        fout.write(line.replace(key, dict1[key]))

fin.close()
fout.close()

Using Regex.使用正则表达式。

Ex:前任:

import re

dict1={'feed-496':'high','feed-497':'low','feed-498':'medium'}

with open(filename) as infile:
    for line in infile:                         #Iterate Each Line
        key = re.search(r'\"(.*?)\"', line)     #Search for key between Quotes
        if key:
            print(line.replace(key.group(1), dict1.get(key.group(1), key.group(1))))    #Replace Value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM