簡體   English   中英

如何在python中從字符串的開頭和結尾去除特殊字符

[英]How to strip special characters from the start and end of the string in python

我在字符串末尾有一個包含特殊字符(!?@ ##。)的句子列表。 我需要脫掉它們。 這是句子列表:

['The first time you see The Second Renaissance it may look boring.', 'Look at it at least twice and definitely watch part 2.', 'It will change your view of the matrix.', 'Are the human people the ones who started the war?', 'Is AI a bad thing?']

我的輸出應該是這樣的:

['The first time you see The Second Renaissance it may look boring', 'Look at it at least twice and definitely watch part 2', 'It will change your view of the matrix', 'Are the human people the ones who started the war', 'Is AI a bad thing']

如果只想從開頭和結尾刪除字符,則可以使用string.strip()方法。

例:

strp_chars = '!?@#$.'
sentence = 'The first time you see The Second Renaissance it may look boring.'
print(sentence.strip(strp_chars))

只需在列表壓縮中將string.strip與所有需要刪除的字符一起使用即可,例如:

In [1]: l = ['The first time you see The Second Renaissance it may look boring.', 'Look at it at least twice and definitely watch part 2.', 'It will change
   ...:  your view of the matrix.', 'Are the human people the ones who started the war?', 'Is AI a bad thing?']

In [2]: p = [i.strip('.,?!') for i in l]

In [3]: p
Out[3]:
['The first time you see The Second Renaissance it may look boring',
 'Look at it at least twice and definitely watch part 2',
 'It will change your view of the matrix',
 'Are the human people the ones who started the war',
 'Is AI a bad thing']

In [4]:

您可以嘗試翻譯方法:

import unicodedata
import sys

data1=['The first time you see The Second Renaissance it may look boring.', 'Look at it at least twice and definitely watch part 2.', 'It will change your view of the matrix.', 'Are the human people the ones who started the war?', 'Is AI a bad thing?']


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

def remove_punctuation(sentence):
    return sentence.translate(data)

for i in data1:
    print(remove_punctuation(i))

輸出:

The first time you see The Second Renaissance it may look boring
Look at it at least twice and definitely watch part 2
It will change your view of the matrix
Are the human people the ones who started the war
Is AI a bad thing

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM