【问题标题】:Remove conjunction from file.txt and punctuation from user input从 file.txt 中删除连词并从用户输入中删除标点符号
【发布时间】:2020-02-11 16:26:49
【问题描述】:

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

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

    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']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 2020-10-04
      • 2015-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多