Stripping everything but alphanumeric chars from a string in Python

前端 未结 11 1435
不思量自难忘°
不思量自难忘° 2020-11-22 10:52

What is the best way to strip all non alphanumeric characters from a string, using Python?

The solutions presented in the PHP variant of this question will probably

11条回答
  •  深忆病人
    2020-11-22 11:26

    If i understood correctly the easiest way is to use regular expression as it provides you lots of flexibility but the other simple method is to use for loop following is the code with example I also counted the occurrence of word and stored in dictionary..

    s = """An... essay is, generally, a piece of writing that gives the author's own 
    argument — but the definition is vague, 
    overlapping with those of a paper, an article, a pamphlet, and a short story. Essays 
    have traditionally been 
    sub-classified as formal and informal. Formal essays are characterized by "serious 
    purpose, dignity, logical 
    organization, length," whereas the informal essay is characterized by "the personal 
    element (self-revelation, 
    individual tastes and experiences, confidential manner), humor, graceful style, 
    rambling structure, unconventionality 
    or novelty of theme," etc.[1]"""
    
    d = {}      # creating empty dic      
    words = s.split() # spliting string and stroing in list
    for word in words:
        new_word = ''
        for c in word:
            if c.isalnum(): # checking if indiviual chr is alphanumeric or not
                new_word = new_word + c
        print(new_word, end=' ')
        # if new_word not in d:
        #     d[new_word] = 1
        # else:
        #     d[new_word] = d[new_word] +1
    print(d)
    

    please rate this if this answer is useful!

提交回复
热议问题