Python 2.7中的Unicode字符的二进制搜索(bisect)

时间:2015-07-01 08:37:35

标签: python python-2.7 unicode

我有2048 Japanese Unicode words已排序列表?page=2,理想情况下,我希望使用二进制搜索进行索引,如{{3}中所述}。 J函数使用binary_search模块中的bisect_left,而不是使用bisect函数索引列表。

list.index

现在,让我们为import bisect def binary_search(a, x, lo=0, hi=None): # can't use a to specify default for hi hi = hi if hi is not None else len(a) # hi defaults to len(a) pos = bisect.bisect_left(a, x, lo, hi) # find insertion point return (pos if pos != hi and a[pos] == x else -1) 中的每个单词编制索引:

words

让我们分开制作一个清单:

words = "そつう れきだい ほんやく わかす りくつ ばいか ろせん やちん そつう れきだい ほんやく わかめ"

>>> words.split() [u'\u305d\u3064\u3046', u'\u308c\u304d\u305f\u3099\u3044', u'\u307b\u3093\u3084\u304f', u'\u308f\u304b\u3059', u'\u308a\u304f\u3064', u'\u306f\u3099\u3044\u304b', u'\u308d\u305b\u3093', u'\u3084\u3061\u3093', u'\u305d\u3064\u3046', u'\u308c\u304d\u305f\u3099\u3044', u'\u307b\u3093\u3084\u304f', u'\u308f\u304b\u3081']`) binary_search进行比较:

list.index

因此,对于>>> [ binary_search(J, x) for x in words.split()] [-1, 2015, 1790, 2039, 1983, -1, 2031, 1919, -1, 2015, 1790, 2040] >>> [ J.index(x) for x in words.split()] [1019, 2015, 1790, 2039, 1983, 1533, 2031, 1919, 1019, 2015, 1790, 2040] u'\u305d\u3064\u3046')而不是索引1019,そつう返回索引-1(失败),因为binary_search计算结果为 1027 pos这两个字(索引1019和1027)都以u'\u305d\u3068\u304b\u3099\u308f'开头,因此这就是问题所在。

如何调整u'\u305d'以查找(日语)Unicode字符的索引?

1 个答案:

答案 0 :(得分:1)

这里显示您的J列表有问题;它没有正确排序。

当我使用requests库加载测试数据文件并对信息进行排序时,它可以正常工作:

 >>> # your bisect function defined
 ...
 >>> import requests
 >>> words = u"そつう れきだい ほんやく わかす りくつ ばいか ろせん やちん そつう れきだい ほんやく わかめ"
 >>> url = 'https://raw.githubusercontent.com/trezor/python-mnemonic/master/mnemonic/wordlist/japanese.txt'
 >>> J = sorted(requests.get(url).text.splitlines())
 >>> [ J.index(x) for x in words.split()]
[1024, 2015, 1787, 2039, 1983, 1601, 2031, 1919, 1024, 2015, 1787, 2040]
>>> [ binary_search(J, x) for x in words.split()]
[1024, 2015, 1787, 2039, 1983, 1601, 2031, 1919, 1024, 2015, 1787, 2040]

请注意,索引与您的测试结果不完全匹配;如果指数偏离3以上,则bisect无法找到结果。