python - 检查句子输入中的关键字,然后检查Python中的文本文件

标签 python

我一直在学习Python,但遇到了一些困难。我想制作一个用户可以输入句子的程序。然后,程序将句子拆分,并根据列表检查单词。如果在列表中找到任何单词,则会在文本文件中查找该单词并打印该单词所在文本文件的行。

到目前为止我有这个:

    def getTakeaway():
    list = ["pizza", "italian", "chinese", "indian"]
    query = input("Please say what take away you'd like").lower()
    if set(list).intersection(query.split()):
        with open('takeaway.txt') as f:
            for line in open('takeaway.txt'):
                if query in line:
                    print (line)
                    break
    else:
        print("sorry not found")
getTakeaway()

它适用于单个单词输入,例如“披萨”,但是当搜索“我想要披萨”等输入时,我什么也没有得到。

提前致谢。

编辑:我根据给出的建议将代码更改为:

def getTakeaway():
    list = ["pizza", "italian", "chinese", "indian"]
    query = input("Please say what take away you'd like").lower()
    query_words = set(list).intersection(query.split())
    if query_words:
        with open('takeaway.txt') as f:
            for line in open('takeaway.txt'):
                if query_words in line:
                    print (line)
                    break
    else:
        print("sorry not found")
getTakeaway()

我收到此错误: 如果 query_words 在行中: 类型错误:“in”需要字符串作为左操作数,未设置

最佳答案

在行

if query_words in line:

您正在使用包含 set(['i', 'would', 'like', 'some', 'pizza']) 的集合。表达式“行中查询”现在将从行中查找集合。您需要迭代集合中的值,就像迭代文件中的行一样:

for word in query_words:
    if word in line:
        ...

关于python - 检查句子输入中的关键字,然后检查Python中的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33723669/

相关文章:

python - 一个函数有两个装饰器,后一个函数没有按预期工作?

python - 访问python列表循环中的第二个值

python - Pandas groupby 滚动分位数

python - 使用张量输入时 Keras 模型预测会发生变化

python celery 没有名为 app.tasks 的模块

python - 当我拖动无框窗口时,如何停用 Windows 任务栏上的鼠标运动 (<Motion-1>)?

python - Pandas :一旦一列达到另一列的某个值,如何返回行值?

python - 返回成功或失败以及函数结果

python - OperatorNotAllowedInGraphError : using a `tf.Tensor` as a Python `bool` is not allowed: (error in tf Cycle GAN)

python - python 导入模块的问题