python删除字符串中重复字符_从Python中删除字符串标点符号的最佳方法

似乎有一个比以下更简单的方法:

1

2

3import string

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

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

有?

在我看来很直接。你为什么要改变它?如果你想更容易的话,就把你刚才写的东西包装在一个函数中。

好吧,用str.translate的副作用来做这项工作,似乎有点刻薄。我在想可能有一些更像str.strip(chars)的东西可以处理整个字符串,而不仅仅是我错过的边界。

也取决于数据。在服务器名称中包含下划线的数据(在某些地方很常见)上使用这个命令可能会很糟糕。只要确保你知道数据,知道它是什么,或者你可以以clbuttic问题的一个子集结束。

也取决于你所说的标点符号。"The temperature in the O'Reilly & Arbuthnot-Smythe server's main rack is 40.5 degrees.只包含一个标点符号,第二个。

我很惊讶没有人提到string.punctuation根本不包括非英语标点符号。我在想。,!?:&215;""?等等。

不适用于Unicode字符串?

@约翰马钦,你忘了' '是标点符号。

从效率的角度看,你不会打败

1s.translate(None, string.punctuation)

对于较高版本的python,请使用以下代码:

1s.translate(str.maketrans('', '', string.punctuation))

它使用一个查找表在C中执行原始字符串操作——除了编写自己的C代码,没有什么比这更好的了。

如果速度不是问题,另一个选择是:

1

2exclude = set(string.punctuation)

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

这比s.replace替换为每个字符要快,但不能像下面计时中看到的那样执行非纯Python方法,如regexes或string.translate。对于这种类型的问题,在尽可能低的水平上做它会有回报。

定时代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25import 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): # From Vinko's solution, with fix.

return regex.sub('', s)

def test_trans(s):

return s.translate(table, string.punctuation)

def test_repl(s): # From S.Lott's solution

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)

结果如下:

1

2

3

4sets : 19.8566138744

regex : 6.86155414581

translate : 2.12455511093

replace : 28.4436721802

感谢您提供的计时信息,我本来想自己做一些类似的事情,但您的设计比我所能做的任何事情都要好,现在我可以将它用作我将来要编写的任何计时代码的模板:)。

很好的回答。您可以通过删除表来简化它。文档说:"对于只删除字符的翻译,将table参数设置为none"(docs.python.org/library/stdtypes.html_str.translate)

对''.join()使用列表理解会使它更快一些,但速度不足以打败regex或translate。请参阅不带&91;&93;、python的列表理解,了解原因。

你能解释一下"从主导入…"的语法吗??

同样值得注意的是,translate()对于str和unicode对象的行为也不同,因此您需要确保始终使用相同的数据类型,但此答案中的方法对这两种类型都同样有效,这很方便。

在python3中,table = string.maketrans("","")应替换为table = str.maketrans({key: None for key in string.punctuation})?

做set(string.punctuation)的目的是什么?它只有独特的价值观。

@Mlissner-效率。它是一个列表/字符串,你需要做一个线性扫描来找出字母是否在字符串中。不过,使用集合或字典,通常会更快(除了非常小的字符串),因为它不必检查每个值。

@sparkandshine是的,除非您必须将每个键的序号映射到替换字符,所以在python 3中,它将是s.translate({ord(c): None for c in string.punctuation})。

为了更新讨论,从python 3.6开始,regex现在是最有效的方法!它几乎比翻译快2倍。而且,套装和替换也不再那么糟糕了!它们都提高了4倍以上。)

在python 3中,翻译表也可以由table = str.maketrans('', '', string.punctuation)docs.python.org/3/library/stdtypes.html_str.maketrans创建。

我得到这个错误TypeError: translate() takes exactly one argument (2 given)。

知道怎么解决这个问题吗

类型错误:translate()只接受一个参数(给定2个)

@是的,读你上面的评论…你用的是Python3,而不是Python2。

正则表达式足够简单,如果你知道的话。

1

2

3import re

s ="string. With. Punctuation?"

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

在上面的代码中,我们用空字符串替换(re.sub)所有非[字母数字字符(w)和空格(s)]。因此。还有?通过regex运行s变量后,变量"s"中将不存在标点符号。

伟大的。你能解释一下吗?

Unicode的,做的工作吗???????????????

解释:"outlier取代需要Word字符(^)或空间与空字符串。要小心,虽然,比赛下划线W太,例如。

"我认为它会sislam与Unicode Unicode与标志集,s = re.sub(r'[^\w\s]','',s, re.UNICODE)IU。在Linux测试它与Python 3它甚至没有标志使用泰米尔语文学?????????????????????????????。。。。。。。

这是一个地方,你应该使用正则表达式。

为了方便使用,我总结了在python 2和python 3中从字符串中去掉标点符号的注意事项。详细描述请参考其他答案。

Python 2

1

2

3

4

5import string

s ="string. With. Punctuation?"

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

new_s = s.translate(table, string.punctuation) # Output: string without punctuation

Python 3

1

2

3

4

5import string

s ="string. With. Punctuation?"

table = str.maketrans({key: None for key in string.punctuation})

new_s = s.translate(table) # Output: string without punctuation

小纸条:你不需要理解做一dict键映射到给定的dictof a None;{key: None for key in string.punctuation}可以取代这是一个dict.fromkeys(string.punctuation)所有工作在C层有一个单一的呼叫。

"谢谢你shadowranger,此更新。

1myString.translate(None, string.punctuation)

啊,我试过了,但在任何情况下都不行。mystring.translate(string.maketrans(",",),string.标点)工作正常。

什么时候不起作用?

注意,对于python 3中的str和python 2中的unicode,不支持deletechars参数。

@AGF:即使在使用字典参数的unicode和py3k情况下,您仍然可以使用.translate()删除标点符号。

mystring.translate(string.maketrans(","),string.punctuation)不与Unicode字符串(发现辛苦)

marcmaxson @工作:myString.translate(str.maketrans("","", string.punctuation))是Unicode字符串在Python 3。虽然只在string.punctuation包括ASCII标点。点击链接在我以前的评论。它显示如何删除所有标点(包括Unicode One)。

TypeError: translate() takes exactly one argument (2 given):(

"briantingle看Python代码:3评论(它在我的护照的一个参数)。链接到Python代码是2,湖和它的作品与Unicode的Python 3适应

我通常用这样的东西:

1

2

3

4

5

6

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

>>> import string

>>> for c in string.punctuation:

... s= s.replace(c,"")

...

>>> s

'string With Punctuation'

一个丑陋的一行:reduce(lambda s,c: s.replace(c, ''), string.punctuation, s)。

很好,但是不能去除一些像长的连字符这样的问题。

string.punctuation只是ASCII码!一种更正确(但也更慢)的方法是使用unicodedata模块:

1

2

3

4

5# -*- coding: utf-8 -*-

from unicodedata import category

s = u'String — with - ?punctation ?...'

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

print 'stripped', s

你可以regex.sub(ur"\p{P}+","", text):

不一定简单,但如果你更熟悉这个家庭的话,那就另当别论了。

1

2

3import re, string

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

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

因为字符串。标点符号有序列,-。以正确的、升序的、无间隔的、ASCII顺序。虽然python有这个权利,但是当您尝试使用string.pu点符号的子集时,它可能会因为意外的"-"而成为一个显示阻止符。

事实上,这仍然是错误的。序列"93"被视为一个转义(巧合的是没有关闭),因此绕过了另一个故障),但没有转义。您应该使用re.escape(字符串、标点符号)来防止这种情况发生。

是的,我省略了它,因为它在示例中起到了保持简单的作用,但是您认为它应该被合并是正确的。

对于python 3 str或python 2 unicode值,str.translate()只接受字典;在该映射中查找代码点(整数),并删除映射到None的任何内容。

删除(一些?)标点符号,使用:

1

2

3

4import string

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

s.translate(remove_punct_map)

dict.fromkeys()类方法使得创建映射变得简单,根据键的顺序将所有值设置为None。

要删除所有标点符号,而不仅仅是ASCII标点符号,您的表需要大一点;请参见J.F.Sebastian的答案(python 3版本):

1

2

3

4

5import unicodedata

import sys

remove_punct_map = dict.fromkeys(i for i in range(sys.maxunicode)

if unicodedata.category(chr(i)).startswith('P'))

支持Unicode,string.punctuation是不够的。我的回答湖

事实上,我的回答:"j.f.sebastian只是使用相同的字符作为一个顶级评为。添加您的Python版本表3。

只有把作品评为最为ASCII字符串。你要明确索赔的Unicode支持。

它j.f.sebastian @:Unicode字符串。IT标准的ASCII标点。我从来没有声称它带所有的标点。点是:-)提供正确的技术研究与unicode对象2 strPython对象。

string.punctuation漏掉了现实世界中常用的大量标点符号。一个适用于非ASCII标点的解决方案如何?

1

2

3

4import regex

s = u"string. With. Some?Really Weird、Non?ASCII。 「(Punctuation)」?"

remove = regex.compile(ur'[\p{C}|\p{M}|\p{P}|\p{S}|\p{Z}]+', regex.UNICODE)

remove.sub(u"", s).strip()

就我个人而言,我认为这是从python字符串中删除标点符号的最佳方法,因为:

它删除所有Unicode标点符号

它很容易修改,例如,如果要删除标点符号,可以删除\{S},但保留类似$的符号。

您可以对要保留的内容和要删除的内容进行具体说明,例如,\{Pd}只删除破折号。

此regex还规范化空白。它将标签、回车和其他奇怪的东西映射到漂亮的单个空间。

这使用了Unicode字符属性,您可以在维基百科上了解更多信息。

下面是一个针对python 3.5的一行程序:

1

2import string

"l*ots! o(f. p@u)n[c}t]u[a'ti"on#$^?/".translate(str.maketrans({a:None for a in string.punctuation}))

这可能不是最好的解决方案,但我就是这样做的。

1

2import string

f = lambda x: ''.join([i for i in x if i not in string.punctuation])

这是我写的一个函数。它不是很有效,但很简单,您可以添加或删除任何您想要的标点:

1

2

3

4

5

6

7def stripPunc(wordList):

"""Strips punctuation from list of words"""

puncList = [".",";",":","!","?","/","\",",","#","@","$","&",")","(","""]

for punc in puncList:

for word in wordList:

wordList=[word.replace(punc,'') for word in wordList]

return wordList

我还没看到这个答案。只需使用regex;它会删除除单词字符(\w和数字字符(\d外的所有字符,后跟空白字符(\s):

1

2

3import re

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

out = re.sub(ur'[^\w\d\s]+', '', s)

是因为它是一个\d冗余\w子集)。

a number of Word字符子集被认为是人物?我的思想一个Word字符可以是任何字符构建真实的Word,例如A ZA Z?

A是的,在"Word"正则表达式包括字母,数字和下划线。请描述一\w湖:在文档docs.python.org / 3 /图书馆/ re.html

正如更新一样,我在python3中重写了@brian示例,并对其进行了更改,以将regex编译步骤移到函数内部。我在这里想的是时间的每一个步骤需要使功能工作。也许您使用的是分布式计算,并且不能在您的工作人员之间共享regex对象,并且需要在每个工作人员处执行re.compile步骤。另外,我还想知道针对python3的两种不同的maketrans实现的时间。

1table = str.maketrans({key: None for key in string.punctuation})

VS

1table = str.maketrans('', '', string.punctuation)

另外,我还添加了另一个方法来使用set,在这里我利用交集函数来减少迭代次数。

这是完整的代码:

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

44import re, string, timeit

s ="string. With. Punctuation"

def test_set(s):

exclude = set(string.punctuation)

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

def test_set2(s):

_punctuation = set(string.punctuation)

for punct in set(s).intersection(_punctuation):

s = s.replace(punct, ' ')

return ' '.join(s.split())

def test_re(s): # From Vinko's solution, with fix.

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

return regex.sub('', s)

def test_trans(s):

table = str.maketrans({key: None for key in string.punctuation})

return s.translate(table)

def test_trans2(s):

table = str.maketrans('', '', string.punctuation)

return(s.translate(table))

def test_repl(s): # From S.Lott's solution

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("sets2 :",timeit.Timer('f(s)', 'from __main__ import s,test_set2 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("translate2 :",timeit.Timer('f(s)', 'from __main__ import s,test_trans2 as f').timeit(1000000))

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

这是我的结果:

1

2

3

4

5

6sets : 3.1830138750374317

sets2 : 2.189873124472797

regex : 7.142953420989215

translate : 4.243278483860195

translate2 : 2.427158243022859

replace : 4.579746678471565

这里有一个没有regex的解决方案。

1

2

3

4

5

6

7import string

input_text ="!where??and!!or$$then:)"

punctuation_replacer = string.maketrans(string.punctuation, ' '*len(string.punctuation))

print ' '.join(input_text.translate(punctuation_replacer).split()).strip()

Output>> where and or then

用空格替换标点符号

将单词之间的多个空格替换为单个空格

删除尾随空格(如果有)条()

1

2

3

4

5

6>>> s ="string. With. Punctuation?"

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

>>> re.split(r'\s*', s)

['string', 'With', 'Punctuation']

请编辑有更多的信息。"试试这个代码和只读"答案是气馁,因为他们searchable不包含的内容,不要解释为什么有人要"试试这个"。

1

2

3import re

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

out = re.sub(r'[^a-zA-Z0-9\s]', '', s)

在不太严格的情况下,使用一行程序可能会有所帮助:

1''.join([c for c in s if c.isalnum() or c.isspace()])

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20#FIRST METHOD

#Storing all punctuations in a variable

punctuation='!?,.:;"\')(_-'

newstring='' #Creating empty string

word=raw_input("Enter string:")

for i in word:

if(i not in punctuation):

newstring+=i

print"The string without punctuation is",newstring

#SECOND METHOD

word=raw_input("Enter string:")

punctuation='!?,.:;"\')(_-'

newstring=word.translate(None,punctuation)

print"The string without punctuation is",newstring

#Output for both methods

Enter string: hello! welcome -to_python(programming.language)??,

The string without punctuation is: hello welcome topythonprogramminglanguage

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20with open('one.txt','r')as myFile:

str1=myFile.read()

print(str1)

punctuation = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"',"'"]

for i in punctuation:

str1 = str1.replace(i,"")

myList=[]

myList.extend(str1.split(""))

print (str1)

for i in myList:

print(i,end='

')

print ("____________")

使用regex函数进行搜索和替换,如下所示。如果必须重复执行该操作,则可以保留一个已编译的regex模式(标点符号)副本,这将加快速度。

是否更正了string.标点符号区域设置?如果是这样,这可能不是最好的解决方案。

我不确定,我没用过。我假设海报/读者会知道他们要替换的标点符号。

嗯……我也不知道。我希望。标点符号可以在本地更正,但我不会依赖它。如果用户有一组特定的字符,那么编译后的regex是一个很好的方法,这可能是正确的。

使用python从文本文件中删除停止字

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20print('====THIS IS HOW TO REMOVE STOP WORS====')

with open('one.txt','r')as myFile:

str1=myFile.read()

stop_words ="not","is","it","By","between","This","By","A","when","And","up","Then","was","by","It","If","can","an","he","This","or","And","a","i","it","am","at","on","in","of","to","is","so","too","my","the","and","but","are","very","here","even","from","them","then","than","this","that","though","be","But","these"

myList=[]

myList.extend(str1.split(""))

for i in myList:

if i not in stop_words:

print ("____________")

print(i,end='

')

这是如何把我们的文件改成大写的或小写字母。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17print('@@@@This is lower case@@@@')

with open('students.txt','r')as myFile:

str1=myFile.read()

str1.lower()

print(str1.lower())

print('*****This is upper case****')

with open('students.txt','r')as myFile:

str1=myFile.read()

str1.upper()

print(str1.upper())

我喜欢使用这样的函数:

1

2

3

4

5

6def scrub(abc):

while abc[-1] is in list(string.punctuation):

abc=abc[:-1]

while abc[0] is in list(string.punctuation):

abc=abc[1:]

return abc

这是剥离从开始和结束字符;使用abc.strip(string.punctuation)而不是那个。它不会删除在搜索中的人物。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值