【问题标题】:split punctuations without using regex不使用正则表达式拆分标点符号
【发布时间】:2021-06-19 13:33:38
【问题描述】:

给定输入:

Democr _acy , is overrat _ed .

期望的输出:

Democracy, is overrated.

这是我的代码:

sentence=input()
punctuation = "!\"#$%&'()*+,-./:;<=>?@[\]^`{|}~"
suffixes = ["acy", "ance", "ence", "dom", "er", "or", "ism", "ist",
             "ty", "ment", "ness", "ship", "sion", "tion", "ate",
            "en", "fy", "ize", "able", "ible", "al",
            "esque", "ful", "ic", "ous", "ish", "ive",
            "less", "ed", "ing", "ly", "ward", "wise"]
sentence_list = sentence.split('_')
c=""
if c not in punctuation:

 print("".join(sentence_list))
elif c in punctuation:
        for c in sentence:
         print("".join(sentence_list).split(c))

如您所见,我的输出有 29 个不同的列表,但我只想要其中一个。 我想从单词中删除 '' 并加入我从中删除 '' 的标点符号和单词。 当我写这样的代码时:

sentence_list = sentence.split('_')
print("".join(sentence_list))

'_'和标点符号消失。我在哪里做错了?

【问题讨论】:

    标签: python-3.x join split punctuation


    【解决方案1】:

    这就是我要解决这个问题的方法。

    def combineSentence(si):
        punctuation = "!\"#$%&'()*+,-./:;<=>?@[\]^`{|}~"
        rslt = ''
        ptr = 0
        while ptr < len(si):
            if si[ptr] not in punctuation and si[ptr] != '_':
                rslt += si[ptr]
            else:
                rslt = rslt[:-1]
                if si[ptr] in punctuation:
                    rslt += si[ptr]
            ptr += 1   
        return rslt       
                
    

    执行combineSentence('Democr _acy , is overrat _ed .') 将产生:

    'Democracy, is overrated.'
    

    【讨论】:

      猜你喜欢
      • 2013-11-22
      • 1970-01-01
      • 2012-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-23
      相关资源
      最近更新 更多