例如,我在tex文件中有多个字符串,如下所示:
"条件Heat_Transfer blah blah blah BCh"
使用python我想:
输出字符串应如下所示:
"条件Heat_Transfer blah blah blah BC Heat_Transfer"
每个字符串的关键字条件和BC保持不变,但Heat_Transfer会发生变化。
答案 0 :(得分:2)
首先需要使用字符串上的.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()
方法将字符串的元素与空格连接。
split_sentence.append(split_sentence[split_sentence.index(keyword)+1])
print " ".join(split_sentence)
答案 1 :(得分:1)
这应该有用。
假设您确定自己的关键字'条件'存在。
str_ = "The conditions Heat_Transfer blah blah blah BC"
list_ = str_.split(" ")
str_ = str_+" "+list_[list_.index("conditions")+1]
否则:
str_ = "The conditions Heat_Transfer blah blah blah BC"
try:
list_ = str_.split(" ")
str_ = str_+" "+list_[list_.index("conditions")+1]
except:
pass
答案 2 :(得分:1)
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
答案 3 :(得分:0)
这可以使用正则表达式完成:
import re
str = "The conditions Heat_Transfer blah blah blah BC"
match = re.search('conditions\s([a-zA-z_\-0-9]+)', str)
word = match.group(1)
print str + ' ' + word
答案 4 :(得分:0)
您可以使用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
如果您沿着分裂路线走下去,那么您可以一次性获取索引:
keywords = {"conditions","BC"}
words = s.split(" ")
inds = (i for i, w in enumerate(words) if w in keywords)
a,b = next(inds), next(inds)
print(a, b)
然后简单地加入适当的地方:
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