【问题标题】:Specific word search in long text for pythonpython的长文本中的特定单词搜索
【发布时间】:2020-05-11 11:00:56
【问题描述】:

非常基本的问题,但有没有办法让我在包含我想要的单词的列表中提取字符串?比如:

wordNeeded=str(input("blue or red?"))

list1=["A blue car", "A blue bike", "A red bike"]

然后它会提取wordNeeded中包含exact字的字符串?

【问题讨论】:

    标签: python list wildcard


    【解决方案1】:

    除其他方法外,您还可以使用列表推导:

    list1 = ["A blue car", "A blue bike", "A red bike"]
    result = [item for item in list1 if wordNeeded in item]
    print(result)
    # ["A red bike"]
    

    或者,您可以将filterlambda 函数结合使用:

    result = filter(lambda x: wordNeeded in x, list1)
    print(list(result))
    

    在这种情况下后者更复杂,但产生相同的结果。


    至于 exact 单词,您要么需要在之前拆分每个项目(+最终将其小写):
    wordNeeded = "blue"
    list1 = ["A blue car", "A blue bike", "A red bike", "bluebells are cool."]
    
    result = [item for item in list1
              if any(wordNeeded.lower() == x.lower() for x in item.split())]
    print(result)
    # ['A blue car', 'A blue bike']
    

    或者完全使用带有单词边界的正则表达式:

    import re
    rx = re.compile(r'\b{}\b'.format(wordNeeded), flags=re.I)
    result = [item for item in list1 if rx.search(item)]
    print(result)
    

    【讨论】:

    • 如果您只想获取单个项目以避免遍历整个列表,请使用 next((s for s in list1 if 'blue' in s), None)
    • @Jan 'item' 代表什么?我没有声明其他任何东西
    • @AaryanPatil:item 是一个循环变量,在遍历一个可迭代对象(在本例中是一个列表)时引用实际元素。
    • 根据“exact 单词”的要求,这可能并不完全符合我们的要求,因为它会选择任何匹配的子字符串...例如:“bluebell”
    • @JonClements:确实,之前可能需要一个带有单词边界的正则表达式或在空格上拆分。
    【解决方案2】:

    你可以像这样使用 for 循环:

    for (word in list1):
      if (wordNeeded in item):
          ...
    

    实际的单词搜索非常简单,并且已经讨论了很多时间:

    Python - Check If Word Is In A String

    https://www.geeksforgeeks.org/python-string-find/

    【讨论】:

    • 这也有帮助!
    【解决方案3】:
    def printList(list, word, list_size): 
        map = [0] * NO_OF_CHARS 
    
        for i in word: 
            map[ord(i)] = 1
    
    
        word_size = len(word) 
        for i in list: 
            count = 0
            for j in i: 
                if map[ord(j)]: 
                    count+=1
    
                    map[ord(j)] = 0
            if count==word_size: 
                print i 
    
            # Set the values in map for next item 
            for j in xrange(len(word)): 
                map[ord(word[j])] = 1
    printList(list1, wordNeeded, len(list1))
    
    

    【讨论】:

      猜你喜欢
      • 2017-08-28
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多