【问题标题】:How to quick find word in English-words-list?如何在英文单词列表中快速查找单词?
【发布时间】:2016-03-01 15:19:04
【问题描述】:

我有单词“somewhat”或“qqqw”,想在英语单词列表中找到它(它存在与否,在列表中)。 如果我有list of str,那么

is_exists = s in english_list

如果我们有大量的单词列表,这种方法会很慢。我认为需要某种数据结构或算法来使其更快更高效

那我该怎么做,有什么建议吗?

【问题讨论】:

    标签: python string search


    【解决方案1】:

    这里有一些很好的比较: https://wiki.python.org/moin/TimeComplexity

    你需要的可能是一套。

    【讨论】:

      【解决方案2】:

      正如建议的那样,创建set 而不是list 会更快。 对于“小”数据文件,list 似乎更快,但一旦文件变大,访问set 就会比列表更快。
      用这样的东西测试它:

      from timeit import default_timer as timer
      import sys
      try:
          lookfor = sys.argv[1]
          pass
      except:
          print "Program requires an word to look for"
          sys.exit()
      wordset = set()
      wordlist = []
      with open("your file name","r") as f:
          for i in f.readlines():
              wordset.update(i.split())
              for x in i.split():
                  wordlist.append(x)
      def testwords(word):
          start= timer()
          if word in wordset: print ("Yes word found")
          else: print ("No word not found")
          end= timer()
          print ("Wordset",str(len(wordset)))
          print (start,end,(end - start)*1000)
          start= timer()
          if word in wordlist: print ("Yes word found")
          else: print ("No word not found")
          end= timer()
          print ("Wordlist",str(len(wordset)))
          print (start,end,(end - start)*1000)
      
      testwords(lookfor)
      

      【讨论】:

        【解决方案3】:

        我在其他主题中找到了答案。对不起,我没有先找到它。

        我需要使用bisect 模块和函数bisect_left。它可以快速找到列表中的项目,排序列表。 它在庞大的列表中速度很快。

        【讨论】:

        • 很高兴听到您自己解决了问题。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-25
        • 1970-01-01
        • 2020-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多