【问题标题】:replacing a word in a string with an element from excel. Python用excel中的元素替换字符串中的单词。 Python
【发布时间】:2021-07-21 05:40:45
【问题描述】:

我需要脚本遍历文件的每一行,如果它从 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)

【问题讨论】:

  • 您是否已有读取 Excel 文件的代码?您需要将代码粘贴为文本,而不是图像。

标签: python excel regex file replace


【解决方案1】:
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():
        pattern=f'^{j}$'
        f1=re.sub(pattern,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']

【讨论】:

  • 谢谢。是的,这段代码有效。但是如果你在文件 R 中添加端口 1/1/15,那么这个端口将被替换为 1/1/1 形式的 T
猜你喜欢
  • 2014-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-14
  • 1970-01-01
  • 2015-07-03
相关资源
最近更新 更多