Home Backend Development Python Tutorial How to remove punctuation marks in python

How to remove punctuation marks in python

Jul 01, 2019 am 09:34 AM

How to remove punctuation marks in python

The method of removing punctuation marks in Python is as follows:

Method 1:

str.isalnum:

S. isalnum() -> bool

Return value: True if string has at least one character and all characters are letters or numbers, otherwise False.

Example:

1

2

3

>>> string = "Special $#! characters   spaces 888323"

>>> ''.join(e for e in string if e.isalnum())

'Specialcharactersspaces888323'

Copy after login

Can only recognize letters and numbers, it is very lethal and will also kill Chinese characters, spaces and the like

Method 2:

string.punctuation

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

import re, string

 

s ="string. With. Punctuation?" # Sample string

 

# 写法一:

out = s.translate(string.maketrans("",""), string.punctuation)

 

# 写法二:

out = s.translate(None, string.punctuation)

 

# 写法三:

exclude = set(string.punctuation)

out = ''.join(ch for ch in s if ch not in exclude)

 

# 写法四:

>>> for c in string.punctuation:

            s = s.replace(c,"")

>>> s

'string With Punctuation'

 

# 写法五:

out = re.sub('[%s]' % re.escape(string.punctuation), '', s)

## re.escape:对字符串中所有可能被解释为正则运算符的字符进行转义

 

# 写法六:

# string.punctuation 只包括 ascii 格式; 想要一个包含更广(但是更慢)的方法是使用: unicodedata module :

from unicodedata import category

s = u'String — with - «Punctuation »...'

out = re.sub('[%s]' % re.escape(string.punctuation), '', s)

print 'Stripped', out

# 输出:u'Stripped String \u2014 with  \xabPunctuation \xbb'

out = ''.join(ch for ch in s if category(ch)[0] != 'P')

print 'Stripped', out

# 输出:u'Stripped String  with  Punctuation '

 

 

# For Python 3 str or Python 2 unicode values, str.translate() only takes a dictionary; codepoints (integers) are looked up in that mapping and anything mapped to None is removed.

# To remove (some?) punctuation then, use:

import string

remove_punct_map = dict.fromkeys(map(ord, string.punctuation))

s.translate(remove_punct_map)

 

 

# Your method doesn't work in Python 3, as the translate method doesn't accept the second argument any more.

import unicodedata

import sys

tbl = dict.fromkeys(i for i in range(sys.maxunicode) if unicodedata.category(chr(i)).startswith('P'))

def remove_punctuation(text):

    return text.translate(tbl)

Copy after login

Method 3:

re

Example:

1

2

3

import re

s ="string. With. Punctuation?"

s = re.sub(r'[^\w\s]','',s)

Copy after login

Test:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

import re, string, timeit

 

s ="string. With. Punctuation"

 

exclude = set(string.punctuation)

table = string.maketrans("","")

regex = re.compile('[%s]' % re.escape(string.punctuation))

 

def test_set(s):

    return ''.join(ch for ch in s if ch not in exclude)

 

def test_re(s):

    return regex.sub('', s)

 

def test_trans(s):

    return s.translate(table, string.punctuation)

 

def test_repl(s):

    for c in string.punctuation:

        s=s.replace(c,"")

    return s

 

print"sets :",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000)

print"regex :",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000)

print"translate :",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000)

print"replace :",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000)

 

out_put:

# sets : 19.8566138744

# regex : 6.86155414581

# translate : 2.12455511093

# replace : 28.4436721802

Copy after login

For more Python-related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of How to remove punctuation marks in python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

See all articles