我正在尝试使用以下数据读取文件
Et1, Arista2, Ethernet1
Et2, Arista2, Ethernet2
Ma1, Arista2, Management1
我需要将文件替换Et
替换为Ethernet
,将Ma
替换为Management
。在它们的末尾,数字应该是相同的。实际输出应如下
Ethernet1, Arista2, Ethernet1
Ethernet2, Arista2, Ethernet2
Management1, Arista2, Management1
我尝试使用正则表达式的代码,我能够解析所有Et1
,Et2
和Ma1
。但无法取代它们。
import re
with open('test.txt','r') as fin:
for line in fin:
data = re.findall(r'\A[A-Z][a-z]\Z\d[0-9]*', line)
print(data)
输出看起来像这样..
['Et1']
['Et2']
['Ma1']
答案 0 :(得分:3)
import re
#to avoid compile in each iteration
re_et = re.compile(r'^Et(\d+),')
re_ma = re.compile(r'^Ma(\d+),')
with open('test.txt') as fin:
for line in fin:
data = re_et.sub('Ethernet\g<1>,', line.strip())
data = re_ma.sub('Management\g<1>,', data)
print(data)
答案 1 :(得分:1)
这个例子遵循Joseph Farah的建议
import csv
file_name = 'data.csv'
output_file_name = "corrected_data.csv"
data = []
with open(file_name, "rb") as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
data.append(row)
corrected_data = []
for row in data:
tmp_row = []
for col in row:
if 'Et' in col and not "Ethernet" in col:
col = col.replace("Et", "Ethernet")
elif 'Ma' in col and not "Management" in col:
col = col.replace("Ma", "Management")
tmp_row.append(col)
corrected_data.append(tmp_row)
with open(output_file_name, "wb") as csvfile:
writer = csv.writer(csvfile, delimiter=',')
for row in corrected_data:
writer.writerow(row)
print data
答案 2 :(得分:0)
以下是您应采取的步骤:
str.replace()
将字符替换为您想要的字词;请记住,任何说&#34; Et&#34; (包括#34;以太网&#34;这个词的开头)将被替换,所以请记住这一点。 Ma和管理层也是如此。 file.write()
的文件中。您可能必须覆盖原始文件。