对于给定的字符串,我有一个空格位置数组,如下所示: [3, 7, 11, 18, 24, 29, 34, 45, 50, 55, 59, 67, 70, 75, 80, 84, 90, 93, 97, 108], 我有一个值数组,它们是页面的边框,所以我需要在字符串中找到一个位置,其中有一个空格,并且它接近给定范围内的某个边框值,例如 +/- 5 个字符像这儿: [37、74、111、148、185、222、259、296、333、370、407]。 我这样创建:
lower_and_higher_bounds = [i for i in range(37,444,37)]
例如,新数组的第一个值应该为 34,因为它是接近 37 的最佳选项,下一个值将是 67,因为它是接近 74 的下一个最佳值,依此类推。我尝试了很多东西,但就是行不通。某些 txt 部分丢失或文本超出边框。有谁知道我该如何解决这个问题?基本上我只需要编写一个计算换行符的函数,这样它就不会在单词中间断行。
lower_and_higher_bounds = [i for i in range(37,444,37)]
def search_cut_positions(space_positions, search_value):
length = len(space_positions)
lower_bound = 0
upper_bound = length - 1
while lower_bound <= upper_bound:
midpoint = (upper_bound + lower_bound) // 2
value_at_midpoint = space_positions[midpoint]
if search_value >= value_at_midpoint - 5 and search_value <= value_at_midpoint:
return value_at_midpoint
elif search_value < value_at_midpoint:
upper_bound = midpoint - 1
elif search_value > value_at_midpoint:
lower_bound = midpoint + 1
return None
def cut_and_display_string(col_position, row_position ,input_string, rows=12):
# Find space positions
stringlen = len(input_string)
space_positions = [i for i in range(stringlen) if input_string[i].isspace()]
cut_array = [0,37]
for i in range(len(lower_and_higher_bounds)):
space_position = search_cut_positions(space_positions, lower_and_higher_bounds[i])
if space_position == None:
cut_array.append(lower_and_higher_bounds[i])
break
else:
cut_array.append(space_position)
# Calculate vertical positions
x_positions = [card_height - i for i in range(20, card_height, 10)]
for i in range(len(cut_array) - 1):
start = cut_array[i]
end = cut_array[i + 1]
chunk = input_string[start:end].strip()
display_position = row_position + x_positions[i]
c.drawString(col_position + 10, display_position, chunk)
我尝试根据单词进行剪切,然后根据字符和固定位置进行剪切。我尝试使用修改后的二分搜索。
IIUC 你只是想在列表中找到最接近给定值的数字。之后,您可以使用 +/- 5 的阈值进行过滤。
import numpy as np
def closest(lst, K):
# find the item in lst which is closest to K
lst = np.asarray(lst)
idx = (np.abs(lst - K)).argmin()
return lst[idx]
threshold = 5
spaces = [3, 7, 11, 18, 24, 29, 34, 45, 50, 55, 59, 67, 70, 75, 80, 84, 90, 93, 97, 108]
out = []
for i in range(37,444,37):
ret = closest(spaces, i)
if abs(ret-i) <= threshold:
out.append(ret)
out
输出:
[34, 75, 108]