从 file.txt 中删除连词并从用户输入中删除标点符号
Remove conjunction from file.txt and punctuation from user input
我想从用户输入的标点符号和连词中清除字符串。连词存储在 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?]
使用列表理解来构建单词并检查该单词是否在您的连词列表中:
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']
我想从用户输入的标点符号和连词中清除字符串。连词存储在 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?]
使用列表理解来构建单词并检查该单词是否在您的连词列表中:
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']