从file.txt中删除连词,并从用户输入中删除标点符号

问题描述 投票:0回答:1

我想从标点和连词的用户输入中清除字符串。连词存储在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: "))

输出

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?]
python list file input punctuation
1个回答
0
投票

使用列表理解来构造单词并检查单词是否在连词列表中:

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']
© www.soinside.com 2019 - 2024. All rights reserved.