在一个关键字后面找到一个词,然后将它粘贴到另一个关键字之后。

2024-10-01 15:31:06 发布

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

例如,我在一个tex文件中有一个多个字符串,如下所示:

"The conditions Heat_Transfer blah blah blah BC"

使用python我想:

  1. 找到“条件”后面的单词(在本例中是热交换器)
  2. 然后在BC后粘贴热传导。在

输出字符串应如下所示:

"The conditions Heat_Transfer blah blah blah BC Heat_Transfer"

对于每个字符串,关键字条件和BC保持不变,但是热传递发生变化。在


Tags: 文件the字符串粘贴条件单词conditionstransfer
3条回答
string = string.split() # split string into list

a = string.index(keyword1) # find index of 1st
b = string.index(keyword2) # find index of 2nd

string.insert(b + 1, string[a + 1]) # insert word
string = ' '.join(string) # join list into string

首先需要使用字符串上的.split()方法在空格上拆分给定的字符串,然后找到关键字的索引,然后将字符串放在字符串末尾的索引旁边,只需将单词连接到初始字符串,中间加一个空格。在

sentence = "The conditions Heat_Transfer blah blah blah BC" 
keyword = "conditions"

split_sentence = sentence.split()
sentence+=" "+split_sentence[split_sentence.index(keyword)+1]

print sentence
>>> The conditions Heat_Transfer blah blah blah BC Heat_Transfer

或者,您可以对list本身执行所有的连接操作,然后使用.join()方法将字符串的元素与空格连接起来。在

^{pr2}$

您可以使用re来查找和替换保留所有空白:

s =  "The conditions Heat_Transfer blah blah blah   BC some other text"
con = re.compile(r"(?<=\bconditions\b)\s+(\S+)")
bc = re.compile(r"(\bBC\b)")
m = con.search(s)
if m:
    print(bc.sub(r"\1"+m.group(), s)) 

The conditions Heat_Transfer blah blah blah   BC Heat_Transfer some other text

如果您是沿着分割路线进行的,那么您可以在一次操作中获得索引:

^{pr2}$

然后在适当的地方加入:

w = words[a+1]
print(" ".join(["BC " + w if ind == b else wrd for ind,wrd in enumerate(words)]))


The conditions Heat_Transfer blah blah blah   BC Heat_Transfer some other text

相关问题 更多 >

    热门问题