简体   繁体   中英

python - How to remove punctuation in between words

I use the code to strip a line of text from punctuation:

line = line.rstrip("\n")
line = line.translate(None, string.punctuation)

The problem is that words like doesn't turn to doesnt so now I want to remove the punctuation only between words but can't seem to figure out a way to do so. How should I go about this?

Edit: I thought about using the strip() function but that will only take effect on the right and left trailing of the whole sentence.

For example:

Isn't ., stackoverflow the - best ?

Should become:

Isn't stackoverflow the best

Instead of the current output:

Isnt stackoverflow the best

Assuming you consider words as groups of characters separated by spaces:

>>> from string import punctuation
>>> line = "Isn't ., stackoverflow the - best ?"
>>> ' '.join(word.strip(punctuation) for word in line.split() 
             if word.strip(punctuation))
"Isn't stackoverflow the best"

or

>>> line = "Isn't ., stackoverflow the - best ?"
>>> ' '.join(filter(None, (word.strip(punctuation) for word in line.split())))
"Isn't stackoverflow the best"
line = line.translate(None, string.punctuation.replace('\'', ''))

这是你想要的吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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