繁体   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