【问题标题】:Check for presence of multiple words in list and return list of boolean检查列表中是否存在多个单词并返回布尔值列表
【发布时间】:2012-06-18 08:46:43
【问题描述】:

我已经定义了一个函数来检查一个或多个单词是否在一个列表中,它工作正常,但现在我想弄清楚我应该如何更改我的代码,所以我得到一个 list 的布尔值取决于单词是否在列表中。这是我一直在摆弄的两个独立函数:

这是没有布尔值的,它可以完美地打印单词以及它们是否出现在文本中,但是该函数不输出布尔值(它只是打印,有点我知道很乱)

def isword(file):
    wordlist=input("Which word(s) would you like to check for in the text? ")
    wordlist=wordlist()
    file=chopup(file) ##This is another function of mine that splits a string(file) into   a list
    for n in range(0,len(wordlist)):
        word=wordlist[n]
        n+=1
        word=word.lower() ##so case doesn't matter when the person enters the word(s)
        if word in file:
            print(word, ":TRUE")
            for i in range(0,len(file)):
                if file[i]==word:
                    print(i)
        else:
            print(word," :FALSE")

这个输出一个布尔值,但仅用于一个单词。我想知道如何将它们组合起来,以便得到一个布尔值列表作为输出,不打印

def isword(file):
    a=True
    wordlist=input("Which word(s) would you like to check for in the text? ")
    wordlist=wordlist()
    file=chopup(file) ##This is another function of mine that splits a string(file) into a list
    for n in range(0,len(wordlist)):
        word=wordlist[n]
        n+=1
        word=word.lower()
        if word in file:
            a=a
        else:
            a=False
    return(a)

我最终得到了这个,它工作得很好(我的变量/函数名称在项目中实际上是法语,因为这是法国大学的家庭作业)

def presmot(fichier):
    result=[]
    listemots=input("Entrez le/les mots dont vous voulez vérifier la présence : ")
    listemots=listemots.split()
    fichier=decoupage(fichier)
    for n in range(0,len(listemots)):
        mot=listemots[n]
        mot=mot.lower()
        def testemot(mot):
            a=True
            if mot in fichier:
                a=a
            else:
                a=False
            return(a)
    result=[(mot,testemot(mot)) for mot in listemots] 
    return(result)

唯一烦人的是布尔值是英文的,哦,好吧!

【问题讨论】:

  • 已编辑以改进代码格式:)
  • 哦,我当时就这么做了!是的,它看起来很糟糕,哎呀。
  • 哈哈,不用担心,只是想帮忙:),你应该把语言放在那里......看起来像 python
  • 是的,是的,感谢您的标记!
  • 添加了你不小心忘记的作业标签;)

标签: python list boolean


【解决方案1】:

获取输入时存在错误。使用 raw_input 而不是输入。

def isword(file):
    wordlist= raw_input("Which word(s) would you like to check for in the text? ").split()
    file=chopup(file)
    return [word.lower() in file for word in wordlist]

仅供参考,您不需要n+=1。 for 循环自动递增 n。

【讨论】:

    【解决方案2】:

    让我们看看:

    • 您现在返回一个布尔值,但它必须是一个列表。所以你应该在函数的开头加上result = [],在结尾加上return result
    • 剩下要做的就是将TrueFalse 附加到该列表中,对于您正在考虑的每个单词。这应该不会太难,因为您已经在计算文件中是否有单词。

    【讨论】:

      猜你喜欢
      • 2018-02-08
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 2023-03-28
      • 2014-03-06
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多