我的代码如下。
我目前有一个 if 语句可以查找特定单词,在本例中为“INGREDIENTS”。
接下来,
我需要打印“INGREDIENTS”中接下来的 2 个单词/字符串,而不是 print("true")
。该单词/字符串在图像中出现一次(“成分”)。
作为示例,我运行 .py 文件,如果我将其包含在脚本中,这就是我的输出:print(text)
Ground Almonds
INGREDIENTS: Ground Almonds(100%).
1kg
我只需要重新编码此部分:
if 'INGREDIENTS' in text:
print("True")
else:
print("False")
所以输出是这样的:
INGREDIENTS: Ground Almonds
因为接下来的两个单词/字符串是 Ground
和 Almonds
Python代码
from PIL import Image
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\Users\gzi\AppData\Roaming\Python\Python37\site-packages\tesseract.exe'
img=Image.open('C:/Users/gzi/Desktop/work/lux.jpg')
text = pytesseract.image_to_string(img, lang = 'eng')
if 'INGREDIENTS' in text:
print("True")
else:
print("False")
最佳答案
如果您不关心百分比并希望避免使用正则表达式
:
string = 'INGREDIENTS: Ground Almonds(100%).'
tokens = string.split()
for n,i in enumerate(tokens):
if 'INGREDIENTS' in i:
print(' '.join(tokens[n:n+3]))
输出:
INGREDIENTS: Ground Almonds(100%).
关于python - 如何查找特定文本并打印其后的接下来的 2 个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57563221/