python - 循环遍历字典以替换文本文件中的多个值
问题描述
我正在尝试更改文本文件中的几个十六进制值。我制作了一个 CSV,其中一列中包含原始值,另一列中包含新值。
我的目标是编写一个简单的 Python 脚本,根据第一列在文本文件中查找旧值,并在第二列中用新值替换它们。
我正在尝试使用字典来促进replace()
我通过循环通过 CSV 创建的这一点。构建它很容易,但是用它来执行 areplace()
并没有成功。当我在脚本运行后打印出值时,我仍然看到原始值。
我已经尝试使用read()
和执行对整个文件的更改来读取文本文件,就像上面一样。
import csv
filename = "origin.txt"
csv_file = 'replacements.csv'
conversion_dict = {}
# Create conversion dictionary
with open(csv_file, "r") as replace:
reader = csv.reader(replace, delimiter=',')
for rows in reader:
conversion_dict.update({rows[0]:rows[1]})
#Replace values on text files based on conversion dict
with open(filename, "r") as fileobject:
txt = str(fileobject.read())
for keys, values, in conversion_dict.items():
new_text = txt.replace(keys, values)
我还尝试将更新后的文本添加到列表中:
#Replace values on text files based on conversion dict
with open(filename, "r") as fileobject:
txt = str(fileobject.read())
for keys, values, in conversion_dict.items():
new_text.append(txt.replace(keys, values))
然后,我尝试使用readlines()
一次一行用新值替换旧值:
# Replace values on text files based on conversion dict
with open(filename, "r") as reader:
reader.readlines()
type(reader)
for line in reader:
print(line)
for keys, values, in conversion_dict.items():
new_text.append(txt.replace(keys, values))
在进行故障排除时,我进行了测试以查看我的 dict 中的键与文件中的文本之间是否有任何匹配:
for keys, values, in conversion_dict.items():
if keys in txt:
print("match")
else:
print("no match")
除了第一行,我的输出match
在每一行都返回。我想通过一些修剪或我可以解决的问题。但是,这证明有匹配项,所以我的代码肯定有其他问题。
任何帮助表示赞赏。
解决方案
起源.txt:
oldVal9000,oldVal1,oldVal2,oldVal3,oldVal69
测试.csv:
oldVal1,newVal1
oldVal2,newVal2
oldVal3,newVal3
oldVal4,newVal4
import csv
filename = "origin.txt"
csv_file = 'test.csv'
conversion_dict = {}
with open(csv_file, "r") as replace:
reader = csv.reader(replace, delimiter=',')
for rows in reader:
conversion_dict.update({rows[0]:rows[1]})
f = open(filename,'r')
txt = str(f.read())
f.close()
txt= txt.split(',') #not sure what your origin.txt actually looks like, assuming comma seperated values
for i in range(len(txt)):
if txt[i] in conversion_dict:
txt[i] = conversion_dict[txt[i]]
with open(filename, "w") as outfile:
outfile.write(",".join(txt))
修改 origin.txt:
oldVal9000,newVal4,newVal1,newVal3,oldVal69
推荐阅读
- sql - 即使在期间没有出现,如何添加类别?
- html - 为什么我不能让它在曲线上标记?
- android - How to get the incoming number of caller?
- javascript - 错误 NG8001:“路由器插座”不是已知元素
- sql - 将整个表格内容从一个表格复制到另一个具有相同列名称和编号的表格
- python - 将不同长度列表的 dict 值转换为一个列表
- javascript - 使用 Ajax、jquery 更改数据库时更新 html 列和表。姜戈
- php - 如何在laravel中将变量从一个页面传递到另一个页面
- angular - Call a function inside ngFor in Angular 9 lose context
- php - Invalid version string "*"