Удалить конъюнкцию из file.txt и пунктуацию из пользовательского ввода - PullRequest
0 голосов
/ 15 октября 2019

Я хочу очистить строку из пользовательского ввода от пунктуации и соединения. соединение сохраняется в файле file.txt (Stop Word.txt)

Я уже попробовал этот код:

f = open("Stop Word.txt", "r")

def message(userInput):
    punctuation = "!@#$%^&*()_+<>?:.,;/"
    words = userInput.lower().split()
    conjunction = f.read().split("\n")
    for char in words:
        punc = char.strip(punctuation)
        if punc in conjunction:
            words.remove(punc)
            print(words)

message(input("Pesan: "))

OUTPUT

when i input "Hello, how are you? and where are you?" 
i expect the output is [hello,how,are,you,where,are,you]
but the output is [hello,how,are,you?,where,are,you?]
or [hello,how,are,you?,and,where,are,you?]

1 Ответ

0 голосов
/ 15 октября 2019

Используйте понимание списка, чтобы составить слова и проверить, есть ли слово в вашем списке соединений:

f = open("Stop Word.txt", "r")

def message(userInput):
    punctuation = "!@#$%^&*()_+<>?:.,;/"
    words = userInput.lower().split()
    conjunction = f.read().split("\n")
    return [char.strip(punctuation) for char in words if char not in conjunction]

print (message("Hello, how are you? and where are you?"))

#['hello', 'how', 'are', 'you', 'where', 'are', 'you']
...