在print语句中突出显示子字符串

2024-04-19 19:24:43 发布

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

我一直在尝试写一个简短的脚本,直接在jupyter笔记本上运行。它只需在文本(平均400字)中滚动,并要求用户提供一个标签。你知道吗

我正在努力寻找一个优雅的解决方案,将突出所有子字符串'欧盟'的文本打印出来。你知道吗

在另一个线程中,我发现了这个printmd函数,我用它突出显示“eu”子字符串。但是,这只适用于第一次出现,也会破坏线条。你知道吗

import sys
from IPython.display import clear_output
from IPython.display import Markdown, display

def printmd(string):
    display(Markdown(string))
printmd('**bold**')

labels = []

for i in range(0,len(SampleDf)):

    clear_output() # clear the output before displaying another article
    print(SampleDf.loc[i]['article_title'])

    lc = SampleDf.loc[i]['article_body'].lower() # the search is case sensitive
    pos = lc.find('eu') # where is the 'eu' mentioned

    print(SampleDf.loc[i]['article_body'][:pos])
    printmd('**eu**')

    print(SampleDf.loc[i]['article_body'][pos+2:])

    var = input("press y if the text is irrelevant" )

    if var == 'y':
        label = 0   # 0 for thrash
    else: 
        label = 1   # 1 for relevant

    labels.append(label)

我很想摆脱由单独的打印声明引入的换行符,并强调所有提到“欧盟”的地方。你知道吗


Tags: theposimportforoutputisdisplayarticle
1条回答
网友
1楼 · 发布于 2024-04-19 19:24:43

将其视为字符串处理,而不是输出问题。如果我正确理解您的需求,这是一个简单的replace用法:

new_text = old_text.replace("eu", "**eu**")

如果您仍然需要单令牌模式,那么 抑制换行很简单,只需使用print参数即可:

print('**eu**', end='')

相关问题 更多 >