用excel中的元素替换字符串中的单词python

qgelzfjb  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(308)

我需要脚本遍历文件的每一行,如果它从excel中找到一个值,它就会替换它

File:
    Port 1/1/1\n
    Description xxx\n
    Port 2/1/3\n
    Description yyy\n
    Port 3/4/2\n
    Description zzz\n
Excel:
1/1/1 - 5/5/5
3/4/2 - 6/6/6

我只能从文件中找到值。但我不知道怎么做替换。有什么想法吗?

import re
import pandas
excel_data_df = pandas.read_excel('swap_ports.xlsx', sheet_name='ports')
print(excel_data_df)
with open("string.txt", "r") as f:
    pattern = r'\d[/]\d[/]\w\d'
    printlines = f.readlines()
    for i in printlines:
        results = re.findall(pattern, i)
        print (results)
uinbv5nw

uinbv5nw1#

import re
dict1={}
with open('r.txt','r') as file:
    f2=file.read().splitlines()
    for i in f2:
        i = i.replace(' ','')
        i = i.split('-')
        dict1[i[0]]=i[1]

with open('t.txt','r') as file:
    f1=file.read()
    final=[]

    for j in dict1.keys():
        f1=re.sub(j,dict1[j],f1)
    final.append(f1)
print(final)

# ['Port 5/5/5\\n\nDescription xxx\\n\nPort 2/1/3\\n\nDescription yyy\\n\nPort 6/6/6\\n\nDescription zzz\\n\n']

相关问题