【问题标题】:Python Function to look for words in any provided sentencePython函数在任何提供的句子中查找单词
【发布时间】:2020-12-27 11:10:39
【问题描述】:

我是编程新手,刚开始通过工作中的在线课程学习 Python。我目前正在讨论编写函数的主题。我认为拥有一个可以让我在提供的任何文本字符串中搜索单词的功能会很有用。

def searchword(enterprise, customer):
if "enterprise" exist:
    result = True
else: 
    result = False
    

我不知道如何编写搜索“企业”和“客户”两个词的函数。而且我不确定如何定义它会在句子字符串中查找单词。

我的工作导师给了我以下功能,以验证我的上述功能是否有效,但我无法让它发挥作用。

def check_searchword():
assert searchword(True, True), "StarFox is an enterprise client."
print('Correct')

【问题讨论】:

  • 您是在寻找单词中的“企业”一词,还是在寻找单词中的可变企业?另外,这个词是什么,你将如何在你的函数中使用它?
  • 您的问题并不是关于booleanboolean-logic,而是关于一般Python 语法。你的问题非常基本,这很好——我们都必须从某个地方开始,但你最好从可行的东西开始,并展示改变它是如何给你带来麻烦的。您在上面提供的代码错误太多,无法有效回答您的问题(即没有定义existresult 未返回等)

标签: python function boolean boolean-logic


【解决方案1】:
import re

def searchword(customerString, searchFor="enterprise"):
    if re.search(searchFor, customerString):
        return True
    else:
        return False


assert searchword("StarFox is an enterprsise client."), True
assert searchword("StarFox is an enxerprsexe client."), True >> Throws AssertionError: True

【讨论】:

    【解决方案2】:

    伟大的开始项目 - 有几点需要注意。首先,Python 可以解决缩进问题,这也是您的导师功能不起作用的原因之一。

    另一种方法是使用 for 循环,它将遍历列表中的每个项目并进行检查。例如:

    test ="StarFox is an enterprise client."
    searchword = ['enterprise', 'customer']
    
    for i in searchword:
      print(i in test) #please note, this will look for the grouping of letters and not a direct work match. So the loop will see 'enterprise' and 'enterprises' as the same thing
    

    最后,这种类型的文本检查最好使用正则表达式。网上有很多关于这方面的教程——自动化无聊的东西这本书是一个很好的资源,还有一些博客文章,比如this one from Towards Data Science

    【讨论】:

      【解决方案3】:

      学习如何编程就是学习将问题分解为可以进一步分解的步骤,等等,直到您到达存在单个命令或语句的步骤。每一步都非常具体 - 成为你自己的恶魔的拥护者。

      如果您正在为工作编程,诀窍是了解许多维护良好的库,这些库允许您在单个语句中编写更复杂的步骤,而不必自己编写所有代码,但作为初学者,自己编写代码会很有启发性。

      如果您正在学习使用函数,要学习的关键是,如果函数更通用,它会更有用,但又不会太通用,以至于对于简单的使用它变得不必要地复杂。

      您提出了一个在提供的字符串中搜索单词的函数。你给出的例子似乎适用于两个特定的词(而且只有这两个)。更通用的方法是在提供的字符串中搜索任意数量的单词。

      如果您解决在字符串中查找多个单词的问题,最明显的步骤是您需要在字符串中查找单个单词并为每个单词执行该任务。如果都找到了,结果应该是True,否则应该是False

      在 Python 中就这么简单:

      >>> 'test' in 'this was a test'
      True
      

      虽然这可能表明您需要其他东西:

      >>> 'is' in 'this was a test'
      True
      

      isthis 的一部分,所以这可能不是您想要的。具体一点 - 您只想匹配整个单词还是部分单词?如果您只想要整个单词,那么您现在有一个新任务:将字符串分解为整个单词。

      类似这样的:

      >>> 'is' in 'this was a test'.split()
      False
      >>> 'test' in 'this was a test'.split()
      True
      

      如果您需要一次又一次地为多件事执行此操作,那么循环听起来很明显:

      >>> text = 'this was a test'
      >>> result = True
      >>> for word in ['test', 'was']:
      ...      result = result and word in text.split()
      

      如果你的任务是在一个函数中捕获它,函数应该通过它的参数(字符串和要查找的单词)接收它完成工作所需的一切,并且它应该返回你期望的一切(a单个布尔值)。

      def search_words(text, words):
          result = True
          for word in words:
              result = result and word in text.split()
          return result
      
      print(search_words('this was a test', ['was', 'test']))
      

      这可行,但效率不高,因为它一次又一次地拆分文本,每个单词一次。此外,在受过训练的 Python 眼中,它看起来并不十分“pythonic”,这通常意味着使用基于 Python 作为语言优势的清晰易读的 Python 编写它。

      例如:

      def search_words(text, words):
          text_words = text.split()
          return all(word in text_words for word in words)
      
      print(search_words('this was a test', ['was', 'test']))
      

      当然,编程的另一个重要方面是满足客户的规范。如果他们坚持他们想要一个搜索这两个特定单词的函数,只使用文本作为参数,你可以使用上面的函数快速给他们:

      def client_search_words(text):
          return search_words(text, ['enterprise', 'customer'])
      
      
      assert client_search_words('StarFox is an enterprsise client'), True
      

      这将引发断言错误,因为它断言了 False 的内容(函数的结果不是 True)。

      我不认为在这里使用断言是一个很好的方法,它是 Python 的一部分,通常远不如你现在想要处理的东西重要。

      【讨论】:

        【解决方案4】:

        要将字符串拆分为所有单词的列表,我将使用string1.split()

        在 python string1 in list1 中,如果 list1 中存在 string1,则返回 True,否则返回 False。

        # This function is used to search a word in a string.
        # it returns True if search_key is present in search_string. 
        # else False.
        
        def searchword(search_key, search_string):
            search_list = search_string.split()
            return search_key in search_list 
        
        search_s = "StarFox is an enterprise client."
        print( searchword("enterprise", search_s) ) 
        

        【讨论】:

          猜你喜欢
          • 2023-03-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-26
          • 2013-04-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多