4

我试图用“H1”替换文件中的字符串,即“H3”,但我只想替换“H3”而不是“mmmoleculeH3”变成“mmmoleculeH1”。我试过重新,但我在 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 的情况下自己做到这一点,那就太好了。在此先感谢。

4

2 回答 2

6

正如其他人所说,这是正则表达式是正确工具的情况。

您可以使用以下方法仅替换整个单词\b

>>> text = 'H3 foo barH3 H3baz H3 quH3ux'
>>> re.sub(r'\bH3\b', 'H1', text)
'H1 foo barH3 H3baz H1 quH3ux'
于 2013-09-13T11:42:33.300 回答
3

由于我一直对没有正则表达式的情况感到好奇,所以这里有一个没有的版本:

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

输出是:

IN:  H3  OUT:  H1
IN:  H3b  OUT:  H3b
IN:  aH3  OUT:  aH3
IN:  H3 mmmoleculeH3 H3  OUT:  H1 mmmoleculeH3 H1
IN:  H3 mmmoleculeH3 H3b  OUT:  H1 mmmoleculeH3 H3b
IN:  H3 mmmoleculeH3 H3b H3  OUT:  H1 mmmoleculeH3 H3b H1

PS:我更喜欢 Daniel Roseman 的解决方案。

于 2013-09-13T12:27:55.130 回答