替换子字符串当它是一个单独的词时

2024-07-05 07:41:39 发布

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

我试图用“H1”替换文件中的字符串,即“H3”,但我只想替换“H3”,而不是“mmmolecleh3”变成“mmmolecleh1”。我尝试过重新编程,但我有限的python知识并没有给我带来任何好处。如果有其他方法很好。脚本我现在使用的是:

#!/usr/bin/python

import fileinput
import sys
def replaceAll(file,searchExp,replaceExp):
    for line in fileinput.input(file, inplace=1):
        if searchExp in line:
            line = line.replace(searchExp,replaceExp)
        sys.stdout.write(line)

replaceAll("boxFile.cof","H3","H1")

如果有什么方法我可以不使用re来做这件事,那就是太好了。谢谢提前。在


Tags: 文件方法字符串inimportsyslineh1
2条回答

正如其他人所说,当regex是合适的工具时,这是一种情况。在

使用\b只能替换整个单词:

>>> text = 'H3 foo barH3 H3baz H3 quH3ux'
>>> re.sub(r'\bH3\b', 'H1', text)
'H1 foo barH3 H3baz H1 quH3ux'

因为我一直很想在没有regex的情况下这样做,下面是一个没有:

MYSTR = ["H3", "H3b", "aH3", "H3 mmmoleculeH3 H3",
         "H3 mmmoleculeH3 H3b", "H3 mmmoleculeH3 H3b H3"]
FIND = "H3"
LEN_FIND = len( FIND )
REPLACE = "H1"

for entry in MYSTR:
    index = 0
    foundat = []
    # Get all positions where FIND is found
    while index < len( entry ):
        index = entry.find( FIND, index )
        if index == -1:
            break
        foundat.append( index )
        index += LEN_FIND

    print "IN: ", entry,
    for loc in foundat:
        # Check if String is starting with FIND
        if loc == 0:
            # Check if String only contains FIND
            if LEN_FIND == len( entry ):
                entry = REPLACE
            # Check if the character after FIND is blank
            elif entry[LEN_FIND] == " ":
                entry = entry[:loc] + REPLACE + entry[loc + LEN_FIND:]
        else:
            # Check if character before FIND is blank
            if entry[loc - 1] == " ":
                # Check if FIND is the last part of the string
                if loc + LEN_FIND + 1 > len( entry ):
                    entry = entry[:loc] + REPLACE + entry[loc + LEN_FIND:]
                # Check if character after FIND is blank
                elif entry[loc + LEN_FIND] == " ":
                    entry = entry[:loc] + REPLACE + entry[loc + LEN_FIND:]

    print " OUT: ", entry

输出为:

^{pr2}$

附言:我更喜欢丹尼尔·罗斯曼的解决方案。在

相关问题 更多 >