简体   繁体   English

如何从字符串中删除标点符号? (蟒蛇)

[英]How Do You Remove Punctuation From A String? (Python)

I need some more help. 我需要更多帮助。 Basically, I'm trying to return the user input with all non-space and non-alphanumeric characters removed. 基本上,我试图返回删除了所有非空格和非字母数字字符的用户输入。 I made code for this much of the way, but I keep getting errors... 我为此编写了很多代码,但是我不断出错。

def remove_punctuation(s):
    '''(str) -> str
    Return s with all non-space or non-alphanumeric  
    characters removed. 
    >>> remove_punctuation('a, b, c, 3!!')
    'a b c 3'
    '''   
    punctuation = '''''!()-[]{};:'"\,<>./?@#$%^&*_~'''  
    my_str =  s 
    no_punct = ""  
    for char in my_str:  
        if char not in punctuation:  
            no_punct = no_punct + char  
    return(no_punct)  

I'm not sure what I'm doing wrong. 我不确定自己在做什么错。 Any help is appreciated! 任何帮助表示赞赏!

I guess that's will work for you ! 我想那对你有用!

def remove_punctuation(s):
    new_s = [i for i in s if i.isalnum() or i.isalpha() or i.isspace()]
    return ''.join(new_s)

Can you use the regular expression module? 可以使用正则表达式模块吗? If so, you can do: 如果是这样,您可以执行以下操作:

import re

def remove_punctuation(s)
    return re.sub(r'[^\w 0-9]|_', '', s)

There is an inbuilt function to get the punctuations... 有一个内置的功能来获取标点符号...

    s="This is a String with Punctuations !!!!@@$##%"
    import string
    punctuations = set(string.punctuations)
    withot_punctuations = ''.join(ch for ch in s if ch not in punctuations)

You will get the string without punctuations 您将获得没有标点符号的字符串

output:
This is a String with Punctuations

You can find more about string functions here 您可以在此处找到有关字符串函数的更多信息

I added the space character to your punctuation string and cleanup up your use of quotes in the punctuation string. 我在标点符号字符串中添加了空格字符,并清理了标点符号字符串中引号的使用。 Then I cleaned up the code in my own style so that can see the small differences. 然后,我以自己的样式整理了代码,以便可以看到微小的差异。

def remove_punctuation(str):
    '''(str) -> str
    Return s with all non-space or non-alphanumeric
    characters removed.
    >>> remove_punctuation('a, b, c, 3!!')
    'a b c 3'
    '''
    punctuation = "! ()-[]{};:'\"\,<>./?@#$%^&*_~"
    no_punct = ""
    for c in str:
        if c not in punctuation:
            no_punct += c
    return(no_punct)

result = remove_punctuation('a, b, c, 3!!')
print("Result 1: ", result)
result = remove_punctuation("! ()-[]{};:'\"\,<>./?@#$%^&*_~")
print("Result 2: ", result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM