Advertisement
shinemic

phrase_shorten

Dec 29th, 2021
1,578
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.31 KB | None | 0 0
  1. from random import choices, randint, shuffle
  2.  
  3. # 加载单词文件
  4. words_list = open('./words_alpha.txt').read().split()
  5. print('#words_list:', len(words_list))
  6. print('sample:', ', '.join(choices(words_list, k=5)))
  7.  
  8. # 生成 {单词长度 => [单词列表]} 的字典,缩短搜寻范围
  9. WORDS_LEN_MAP = {}
  10. for word in words_list:
  11.     WORDS_LEN_MAP.setdefault(len(word), []).append(word)
  12.  
  13. def phrase_shorten(phrase, fetchone=True, randomize=False):
  14.     matches = []
  15.     target_len = len(phrase.split())
  16.     words_pool = WORDS_LEN_MAP[target_len]
  17.     if randomize:
  18.         shuffle(words_pool)
  19.     for word in WORDS_LEN_MAP[target_len]:
  20.         if all([c in w for c, w in zip(word, phrase.lower().split())]):
  21.             matches.append(word.upper())
  22.             if fetchone:
  23.                 break
  24.  
  25.     return matches
  26.  
  27.  
  28. phrases = [
  29.     'Alabama Power Production Landscape Enterprise',
  30.     'Locus Webnar River Hippo Enterprise Rev',
  31.     *[
  32.         ' '.join(word.title() for word in choices(words_list, k=randint(5, 15)))
  33.         for _ in range(8)
  34.     ]
  35. ]
  36. for i, phrase in enumerate(phrases, 1):
  37.     print(f'#{i}')
  38.     phrase_shortened = phrase_shorten(phrase, True, True)
  39.     print('{} => {}'.format(
  40.         phrase,
  41.         phrase_shortened[0] if phrase_shortened else '(not found)'
  42.     ))
  43.     print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement