第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

循環(huán)遍歷字典以替換文本文件中的多個值

循環(huán)遍歷字典以替換文本文件中的多個值

暮色呼如 2023-04-18 16:44:58
我正在嘗試更改文本文件中的幾個十六進制值。我制作了一個 CSV,其中一列包含原始值,另一列包含新值。我的目標(biāo)是編寫一個簡單的 Python 腳本,根據(jù)第一列在文本文件中查找舊值,并在第二列中用新值替換它們。我正在嘗試使用字典來促進replace()我通過循環(huán) CSV 創(chuàng)建的字典。構(gòu)建它非常容易,但是使用它來執(zhí)行一個任務(wù)replace()還沒有成功。當(dāng)我在腳本運行后打印出這些值時,我仍然看到原始值。我試過read()像上面那樣使用和執(zhí)行對整個文件的更改來讀取文本文件。import csvfilename = "origin.txt"csv_file = 'replacements.csv'conversion_dict = {}# Create conversion dictionarywith 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 dictwith 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 dictwith 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 dictwith 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))在進行故障排除時,我運行了一個測試,看看我的字典中的鍵和文件中的文本是否匹配:for keys, values, in conversion_dict.items():    if keys in txt:        print("match")    else:        print("no match")match除了第一行,我的輸出在每一行都返回。我想通過一些修剪或其他東西我可以解決這個問題。但是,這證明存在匹配項,因此我的代碼一定存在其他問題。任何幫助表示贊賞。
查看完整描述

1 回答

?
幕布斯7119047

TA貢獻1794條經(jīng)驗 獲得超8個贊

來源.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


查看完整回答
反對 回復(fù) 2023-04-18
  • 1 回答
  • 0 關(guān)注
  • 118 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號