【发布时间】:2020-07-20 04:34:45
【问题描述】:
我想逐行解析文件并将固定标点替换为另一个标点(例如,句点“/”与斜杠“.”)仅当该行中的该字符串包含某个变量时
示例:仅当字符串包含 Fx 时才替换
line1: test1/test2
line2: .test + e/y + Fx/var1/var2
输出:
line1: test1/test2
line2: .test + e/y + Fx.var1.var2
我该怎么做呢?到目前为止的代码,但我知道它不起作用
import os
textToFind = '/'
textToReplace = '.'
sourcepath = os.listdir('InputFiles/')
def lines_that_contain(string, fp):
return [line for line in fp if string in line]
for file in sourcepath:
inputFile = 'InputFiles/'+ file
print('Conversion is ongoing for:' +inputFile)
with open(inputFile, 'r') as inputFile:
for line in lines_that_contain("Fx.", inputFile):
print('found Fx.')
fileData = fileData.replace(textToFind, textToReplace)
freq2 = 0
freq2 = fileData.count(textToFind)
destinationPath = 'OutputFile/' + file
with open(destinationPath, 'w') as file:
file.write(fileData)
print ('Total %d Record Replaced' %freq2)
else:
print('Did not find selected strings')
【问题讨论】:
-
Stackoverflow 上有各种示例解释了实现此目的的方法。例如stackoverflow.com/questions/17140886/…
-
但我知道这行不通 你能说得更具体些吗?顺便说一句,变量和函数名称应遵循
lower_case_with_underscores样式。
标签: python file parsing search replace