【问题标题】:New to Python - operator // [closed]Python 新手 - 运算符 // [关闭]
【发布时间】:2019-06-05 17:15:38
【问题描述】:

我找到了一些应该可以工作的代码,但没有。我做错了什么/丢失了?

来源:How to find table like structure in image

def find_table_in_boxes(boxes, cell_threshold=10, min_columns=2):
    for box in boxes:
        (x, y, w, h) = box
        print(box)
        col_key = x // cell_threshold

if __name__ == '__main__':
    text_boxes = [
        {
            'x': 123,
            'y': 512,
            'w': 100,
            'h': 150
        },
        {
            'x': 500,
            'y': 512,
            'w': 100,
            'h': 150
        }
    ]
    cells = find_table_in_boxes(text_boxes)

错误

# python test.py
{'x': 123, 'w': 100, 'y': 512, 'h': 150}
Traceback (most recent call last):
  File "test.py", line 22, in <module>
    cells = find_table_in_boxes(text_boxes)
  File "test.py", line 5, in find_table_in_boxes
    col_key = x // cell_threshold
TypeError: unsupported operand type(s) for //: 'str' and 'int'

【问题讨论】:

  • 阅读错误——上面写着unsupported operand types(s) for //: 'str' and 'int'。这意味着您正在尝试将字符串和整数相除。
  • print(x, y, w, h)看看你在那里做什么。
  • (x, y, w, h) = box更改为(x, y, w, h) = box["x"], box["y"], box["w"], box["h"]
  • 您正在尝试在 int 和 string 上进行除法
  • 查看这个可爱的debug 博客寻求帮助。 “看代码”并不是一个特别详细或准确的调试策略。去过那里,做到了,用所有的T恤做了被子......

标签: python


【解决方案1】:

它告诉你x 是一个字符串。它来自boxes,它来自text_boxes。您不能使用以下方法解压字典值:

    (x, y, w, h) = box

试试这个:

x = box["x"]
y = box["y"]
w = box["w"]
h = box["h"]

另一种选择是:

def _find_table_in_box(cell_threshold, x, y, w, h):
    print(x, y, w, h)
    col_key = x // cell_threshold


def find_table_in_boxes(boxes, cell_threshold=10, min_columns=2):
    for box in boxes:
        _find_table_in_box(cell_threshold, **box)

【讨论】:

  • ...或x = int(box["x"])
  • 另一个更紧凑的选项是(x, y, w, h) = (box[i] for i in 'xywh')
  • @barny 目的是什么?
  • 或者只是使用box['x'],因为这是他们访问的唯一值。
  • 可以(x, y, w, h) = box解压字典,你只是得到键(str),而不是值(int
猜你喜欢
  • 2011-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-18
  • 2015-01-28
  • 2011-06-21
  • 2012-12-21
相关资源
最近更新 更多