Поиск слов в текстовом документе, python - PullRequest
0 голосов
/ 12 июля 2020

У меня есть этот простой код, который читает текстовый файл и принимает слово от пользователя, чтобы проверить, есть ли это слово в текстовом документе или нет. Похоже, это работает только для одного слова. Мне нужно изменить этот код, чтобы пользователь мог вводить два или более слов. Пример; GOING HOME вместо HOME. Любая помощь, пожалуйста.

word = input('Enter any word that you want to find in text File :')
f = open("AM30.EB","r")
if word in f.read().split():
    print('Word Found in Text File')
else:
    print('Word not found in Text File')

Ответы [ 3 ]

0 голосов
/ 12 июля 2020

Это решения с учетом регистра!

Все слова в запросе отдельно:

words = input('Enter all words that you want to find in text File: ').split()
f_data = []
with open("AM30.EB", "r") as f:
    f_data = f.read().split()
results = list(map(lambda x: any([y == x for y in f_data]), words))
print("Found ")
for i in range(len(words)): 
    print(f"'{words[i]}'", end="")
    if i < len(words) - 1:
        print("and", end="")
print(f": {all(results)}")

Любое слово в запросе:

words = input('Enter any word that you want to find in the text File: ').split()
f_data = []
with open("AM30.EB", "r") as f:
    f_data = f.read().split()
results = list(map(lambda x: any([y == x for y in f_data]), words))
if any(results):
    for i in range(len(words)):
        print(f"Found '{words[i]}': {results[i]}")

Точная фраза в запросе:

phrase = input('Enter a phrase that you want to find in the text File: ')
f_data = ""
with open("AM30.EB", "r") as f:
    f_data = f.read()
print(f"Found '{phrase}': {f_data.count(phrase) > 0}")
0 голосов
/ 12 июля 2020

Это чувствительно к регистру и проверяет каждое слово отдельно. Не уверен, что это то, что вы искали, но надеюсь, что это поможет!

file1 = open('file.txt', 'r').read().split()

wordsFoundList = []

userInput = input('Enter any word or words that you want to find in text File :').split()
for word in userInput:
    if word in file1:
        wordsFoundList.append(word)

if len(wordsFoundList) == 0:
    print("No words found in text file")
else:
    print("These words were found in text file: " + str(wordsFoundList))
0 голосов
/ 12 июля 2020

Я не уверен, что это именно то, что вы ищете

f = open("AM30.EB","r")

word_list = []

while True:
    word = input('Enter any word that you want to find in text File or 1 to stop entering words :')
    if word == "1": break
    word_list.append(word)

file_list = f.read().split()

for word in word_list:
    if word in file_list:
        print("Found word - {}".format(word))
    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...