Python字符串。替换候补

2024-06-28 20:53:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要Python字符串操作方面的帮助(我将之前的冗长问题归结为下面这个问题)。在

对于文件中的这一行:

L20B, CVS=1, HTYP=16, MLV=25

第二个字段可以是CVS或VS。相关数据将一直显示到行尾。在

需要用另一个字符串替换以CVS或VS开头的部分:

^{pr2}$

示例:

old line: L20B, CVS=1, HTYP=16, MLV=25
new line: L20B, CFIXD(0,1,0)

Old line: T10, M312, P10, Z3710, CL=L1, RH=1  (here, identify RH only and replace with)
New line: T10, M312, P10, Z3710, CL=L1, FIXD(0,1,0)

Old line: T20, M312, P20, Z100, CKR=10000 DV(0,1,0) 
New line: T20, M312, P20, Z100, CLS(0,1,0), MU=0.35

So, the replacement string keeps changing with what is found.
CVS or VS (till end of line) is replaced with CFIXD(0,1,0) or FIXD(0,1,0)
CRH or RH (till end of line) is replaced with CVR(0,1,0) or VR(0,1,0)
CFIXD or FIXD (till end of line) is replaced with CVR(0,1,0) or VR(0,1,0)
20 other variants.

Also, is it possible to modify the re.sub() expression to identify something in the search string and carry it over to the replacement string?
For e.g., 
Search for CFIXD(x,y,z) - replace with CVR (x,y,z) 

我无法搜索精确的子字符串(“CVS=1,HTYP=16,MLV=25”),因为CVS(或VS)后面的数据可能有很多不同的变化,比如

CVS=2, HTYP=11, MLV=25 
VS=4, HTYP=9, MLV=5      etc. 

你看到的长度也可能不同。我唯一能确定的是,以CVS或VS开头的字符串一直到那行的末尾。据我所知,字符串。替换不会工作,因为上面的长度和数据变化。在

有现成的Python方法吗?或者我必须写一个小程序来做这个?我可以找到索引(使用字符串。查找)到VS或CVS,然后替换从该点到行尾的所有内容,是吗?我知道有一个简单的(对我来说)regex方法。谢谢。在


Tags: orthe数据字符串iswithlinecvs
2条回答

您可以使用正则表达式,但对我来说,将字符串拆分为一个列表会更简单:

line = "L20B, CVS=1, HTYP=16, MLV=25"

line = line.split(", ")
if line[1].startswith("CVS="):
    line[1:] = ["CFIXD(0,1,0)"]
elif line[1].startswith("VS="):
    line[1:] = ["FIXD(0,1,0)"]

line = ", ".join(line)

这两个案例可以与一些拼图扑克相结合,因为它们相当相似,但它们似乎以这种方式非常可读。在

使用正则表达式:

import re
re.sub(r'(C|)VS=.*', r'\1FIXD(0,1,0)', line)

说明:

^{pr2}$

示例:

>>> re.sub(r'(C|)VS=.*', r'\1FIXD(0,1,0)', 'L20B, CVS=1, HTYP=16, MLV=25')
'L20B, CFIXD(0,1,0)'
>>> re.sub(r'(C|)VS=.*', r'\1FIXD(0,1,0)', 'L20C, VS=4, HTYP=9, MLV=5')
'L20C, FIXD(0,1,0)'

编辑:根据您的编辑,以下是几种不同情况下的备选方案:

  • CVS或VS->;CFIXD(0,1,0)或FIXD(0,1,0)

    re.sub(r'(C|)VS=.*', r'\1FIXD(0,1,0)', line)
    
  • CRH或RH->;CVR(0,1,0)或VR(0,1,0)

    re.sub(r'(C|)RH=.*', r'\1VR(0,1,0)', line)
    
  • CFIXD(x,y,z)或VIXD(x,y,z)—>;CVR(x,y,z)或VR(x,y,z)

    re.sub(r'(C|)FIXD(\([^)]*\)).*', r'\1VR\2', line)
    

(\([^)]\)).*说明:

(         # start second capture group
   \(       # match a literal '('
   [^)]*    # match any number of characters that are not ')'
   \)       # match a literal ')'
)         # end capture group
.*        # match to the end of the line

相关问题 更多 >