这不是最优化的实现,但值得得到启发。
data = {'text': ['This is an example text that I use in order to',
'Discussion: We are examining the possibility of the'],
'in': [[2], [3]],
'tar': [[6], [6, 7]]}
df = pd.DataFrame(data)
cols = list(df.columns)[1:]
new_text = []
for idx, row in df.iterrows():
temp = list(row['text'].split())
for pos, word in enumerate(temp):
for col in cols:
if pos in row[col]:
temp[pos] = f'<{col.upper()}>{word}</{col.upper()}>'
new_text.append(' '.join(temp))
df['text'] = new_text
print(df.text.to_list())
输出:
['This is <IN>an</IN> example text that <TAR>I</TAR> use in order to',
'Discussion: We are <IN>examining</IN> the possibility <TAR>of</TAR> <TAR>the</TAR>']
更新 1
合并连续出现的相似标签可以如下完成:
data = {'text': ['This is an example text that I use in order to',
'Discussion: We are examining the possibility of the'],
'in': [[2], [3, 4, 5]],
'tar': [[6], [6, 7]]}
df = pd.DataFrame(data)
cols = list(df.columns)[1:]
new_text = []
for idx, row in df.iterrows():
temp = list(row['text'].split())
for pos, word in enumerate(temp):
for col in cols:
if pos in row[col]:
temp[pos] = f'<{col.upper()}>{word}</{col.upper()}>'
new_text.append(' '.join(temp))
df['text'] = new_text
for col in cols:
df['text'] = df['text'].apply(lambda text:text.replace("</"+col.upper()+"> <"+col.upper()+">", " "))
print(df.text.to_list())
输出:
['This is <IN>an</IN> example text that <TAR>I</TAR> use in order to', 'Discussion: We are <IN>examining the possibility</IN> <TAR>of the</TAR>']