在Python中使用.split隔离未定义的关键字

2024-09-30 18:31:35 发布

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

我正在拍摄一个图像,通过pytesseract运行它来获得一个文本列表,并将该列表保存为一个变量:

img = Image.open(path_to_some_image)
imgtxt = pytesseract.image_to_string(img)
print(imgtxt)

>> Some text here
keyword
Random strings
Random chars

我的挑战是在没有定义它的情况下获取keyword,因为它会根据程序运行的时间而变化。我发现keyword总是跟在Some text here后面,其中Somehere总是恒定的,并且text在两个单词之间波动,所以我在here处分割输出。现在,我得到以下信息:

print(imgtxt.split("here",1)[1])

>> keyword
Random strings
Random chars

这将删除keyword之前的所有内容,而不定义它,但现在我想删除之后的所有内容。那么,我的问题是,我怎样才能去掉Random stringsRandom chars,而不把keyword变成一个变量呢?你知道吗


Tags: totextimage列表imghere定义random
1条回答
网友
1楼 · 发布于 2024-09-30 18:31:35

您可以再拆分一次,但这次得到第一项:

imgtxt.split("here", 1)[1].strip().split("\n", 1)[0]

为我工作:

In [1]: imgtxt = """Some text here
        keyword
        Random strings
        Random chars"""
In [2]: imgtxt.split("here", 1)[1].strip().split("\n", 1)[0]
Out[2]: 'keyword'

相关问题 更多 >