简体   繁体   English

如何在Python中的文本文件中搜索多个关键字

[英]How to search for multiple keywords in a textfile in Python

Lets say keywords1.txt contains the following: 可以说keyword1.txt包含以下内容:

Broken Screen

Then I write this program: 然后我写这个程序:

sentence = input("Input your sentence: ")
if open('keywords1.txt').read() in sentence:
    print("hello there")

I wanted it to display 'hello there' whenever i say for example: my screen is broken 我想让它在每次例如说:“我的屏幕坏了”时显示“你好”

But it doesn't work. 但这是行不通的。 Putting those wods in a textfile as a list still doesn't work: 将这些杂音作为列表放置在文本文件中仍然不起作用:

Broken
Screen

Here is a basic algorithm for that. 这是一个基本的算法。 Maybe there is some function in python to make it easy, but this is the most basic code. 也许python中有一些函数可以简化它,但这是最基本的代码。

sentence = input("Input your sentence: ")
findCount = 0
lines = 0
fLines = open('keywords1.txt').readlines()
for line in fLines:
    lines += 1
    if line in sentence:
       findCount += 1
if lines == findCount:
   print("hello there")

Check re module 检查重新模块

Maybe a re.match or re.find 可能是重新匹配或重新查找

Regards 问候

You can use the set method issubset to do that: 您可以使用set方法issubset来做到这一点:

sentence = input("Input your sentence: ")
A = open('keywords1.txt').read().split('\n') # or any other separator
B = sentence.split()
A, B = set(A), set(B)  

if A.issubset(B) :
    print("hello there")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM