python-3.x 删除标点符号和小写字符串

xnifntxz  于 2023-01-06  发布在  Python
关注(0)|答案(2)|浏览(133)

我得编一个能接收输入的代码(文本),去掉所有的标点符号,全部小写。我写了我知道的代码,但它似乎没有给予我想要的结果。开始时,我做了一个简单的lower函数。尽管它似乎不起作用。为了去掉所有标点符号,我列出了所有可能的标点符号,并创建了一个变量,该变量将不断更新到下一个然后用一个split函数来运行它。2我也用一个main函数来调用我所有的函数。3我不知道这是否是我的问题的原因。4或者如果我在类中这样做会更容易。5有什么意见吗?

import string
punctuations = [".", ",", "?", ";", "!", ":", "'", "(", ")", "[", "]", "\"", "...", "-", "~", "/", "@", "{", "}", "*"]
text= str(input("Enter a text: "))
text_Lower=text.lower()
def remove_punctuation(self):
    for i in punctuations:
        str2=punctuations[i]
        self.split(str2= "")
    print(self)

#def remove_cword():
#def fequent_word():
#def positive_word():



def __main__():
    print("Here is your text in lower case: \n")
    print(text_Lower)
    text_Punct=remove_punctuation(text_Lower)
    print(text_Punct)
xqnpmsa8

xqnpmsa81#

punctuations = [".", ",", "?", ";", "!", ":", "'", "(", ")", "[", "]", "\"", "...", "-", "~", "/", "@", "{", "}", "*"]

def remove_punctuation(text_Lower):
    for i in punctuations:
        text_Lower = text_Lower.replace(i, "")

    return text_Lower
    

def main():
    text = str(input("Enter a text: "))

    text_Lower = text.lower()

    text_Punct = remove_punctuation(text_Lower)

    print("Here is your text in lower case:")
    print(text_Lower)

    print("Here is your text in lower case without punctuation:")
    print(text_Punct)

main()
xpcnnkqh

xpcnnkqh2#

你可以把这个问题换一换不用问 * 我想删除哪些字符 *,你可以问 * 我想保留哪些字符 *,看起来你想保留所有的字母,数字或空格,你可以用re library通过regex很简单地做到。

import re

def remove_non_alphanumeric(s):
    return re.sub(r'[^a-zA-Z0-9]\s', '', s)

def test_remove_non_alphanumeric():
    assert remove_non_alphanumeric('Hello, World! 123') == 'Hello World 123'
    assert remove_non_alphanumeric('abcd1234') == 'abcd1234'
    assert remove_non_alphanumeric('!!!') == ''
    assert remove_non_alphanumeric('a b c d') == 'a b c d'
    assert remove_non_alphanumeric('1 2 3 4') == '1 2 3 4'
    assert remove_non_alphanumeric('a@b#c$d%') == 'abcd'
    assert remove_non_alphanumeric('1!2@3#4$') == '1234'
    assert remove_non_alphanumeric('a\nb\tc\rd') == 'a\nb\tc\rd'

test_remove_non_alphanumeric()

相关问题