Python用户输入匹配列表和文件



创建一个python代码,用户输入匹配word和file列表。

例如

list = ["banana", "apple"]
file = open("file_path", "r")
search_word = input("Search the word you want to search: ")
for search_word in file.read()
and search_word in list
print("Search word is in the list and in the file")
else:
print("Search word is not matches")

如果搜索词不在列表中,则不需要搜索文件的内容以寻找匹配,因为它不满足第一个条件。可以测试该条件,如果为false则不需要搜索文件。

您可以做一个简单的字符串测试,如果在文件内容中找到它。

if search_word in data:
print("match")

但是,包含搜索词的单词也将匹配(例如菠萝将与苹果匹配)。

您可以使用正则表达式来检查该单词是否包含在文件中的任何位置。b元字符匹配单词的开头或结尾,例如apple将不匹配单词pineapple(?i)标志进行不区分大小写的搜索,因此单词apple匹配apple,等等。

你可以试试这样做。

import re
list = ["banana", "apple"]
search_word = input("Search the word you want to search: ")    
if search_word not in list: 
# if not in list then don't need to search the file
found = False
else:
with open("file_path", "r") as file:
data = file.read()
found = re.search(fr'(?i)b{search_word}b', data)
# now print results if there was a match or not
if found:
print("Search word is in the list and in the file")
else:
print("Search word does not match")

最新更新