answer 716 Từ góc độ hiệu quả, bạn sẽ không đánh bại s.translate[None, string.punctuation] Đối với các phiên bản cao hơn của Python, sử dụng mã sau: s.translate[str.maketrans['','', string.punctuation]] Nó đang thực hiện các thao tác chuỗi thô trong C bằng bảng tra cứu - sẽ không có nhiều thứ sẽ đánh bại điều đó ngoài việc viết mã C của riêng bạn. Nếu tốc độ không phải là một mối lo, thì một lựa chọn khác là: exclude = set[string.punctuation] s =''.join[ch for ch in s if ch not in exclude] Tốc độ này nhanh hơn s.replace với mỗi char, nhưng sẽ không thực hiện cũng như các cách tiếp cận python không thuần túy như regexes hoặc string.translate, như bạn có thể thấy trong các khoảng thời gian dưới đây. Đối với loại vấn đề này, làm nó ở mức độ thấp nhất có thể sẽ được đền đáp. Mã thời gian: 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 notin 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 solutionfor 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] Điều này cho kết quả như sau: sets :19.8566138744 regex :6.86155414581 translate :2.12455511093 replace :28.4436721802 716 hữu ích 5 bình luận chia sẻ answer 103 Biểu thức thông thường là đủ đơn giản, nếu bạn biết chúng. import re s ="string. With. Punctuation?" s = re.sub[r'[^\w\s]','',s] Trong
đoạn mã trên, chúng tôi đang thay thế [re.sub] tất cả NON [ký tự chữ và số [\ w] và dấu cách [\ s]] bằng chuỗi trống. 103 hữu ích 5 bình luận chia sẻ answer 58 Để thuận tiện cho việc sử dụng, tôi tổng hợp ghi chú về dấu chấm câu từ một chuỗi trong cả Python 2 và Python 3. Vui lòng tham khảo các câu trả lời khác để biết mô tả chi tiết. Con trăn 2 import string s ="string. With. Punctuation?" table = string.maketrans["",""] new_s = s.translate[table, string.punctuation]# Output: string without punctuation Con trăn 3 import string s ="string. With. Punctuation?" table = str.maketrans[{key:Nonefor key in string.punctuation}] new_s = s.translate[table]# Output: string without punctuation 58 hữu ích 2 bình luận chia sẻ answer 50 myString.translate[None, string.punctuation] 50 hữu ích 5 bình luận chia sẻ answer 25 Tôi thường sử dụng một cái gì đó như thế này: >>> s = "string. With. Punctuation?"# Sample string>>>import string >>>for c in string.punctuation:... s= s.replace[c,""]...>>> s 'string With Punctuation' 25 hữu ích 2 bình luận chia sẻ answer 22 string.punctuationlà ASCII chỉ ! Một cách chính xác hơn [nhưng cũng chậm hơn nhiều] là sử dụng mô-đun unicodingata: # -*- 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 22 hữu ích 1 bình luận chia sẻ answer 20 Không nhất thiết phải đơn giản, nhưng một cách khác, nếu bạn quen thuộc hơn với gia đình re. import re, string s ="string. With. Punctuation?"# Sample string out = re.sub['[%s]'% re.escape[string.punctuation],'', s] 20 hữu ích 3 bình luận chia sẻ answer 12 Đối với các giá trị Python 3 strhoặc Python 2 unicode, str.translate[]chỉ mất một từ điển; các điểm mã [số nguyên] được tra cứu trong ánh xạ đó và mọi thứ được ánh xạ tới Nonesẽ bị xóa. Để xóa dấu chấm [một số?] Sau đó, sử dụng: import string remove_punct_map = dict.fromkeys[map[ord, string.punctuation]] s.translate[remove_punct_map] Các dict.fromkeys[]phương pháp lớp học làm cho nó tầm thường để tạo ra các bản đồ, thiết lập tất cả các giá trị Nonedựa trên chuỗi các phím. Để xóa tất cả dấu câu, không chỉ dấu chấm câu ASCII, bảng của bạn cần lớn hơn một chút; xem câu trả lời của JF Sebastian [phiên bản Python 3]: import unicodedata import sys remove_punct_map = dict.fromkeys[i for i in range[sys.maxunicode]if unicodedata.category[chr[i]].startswith['P']] 12 hữu ích 4 bình luận chia sẻ answer 11 string.punctuationbỏ lỡ vô số dấu chấm câu thường được sử dụng trong thế giới thực. Làm thế nào về một giải pháp hoạt động cho dấu câu không ASCII? import 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[] Cá nhân, tôi tin rằng đây là cách tốt nhất để xóa dấu câu khỏi chuỗi trong Python vì:
Điều này sử dụng các thuộc tính ký tự Unicode, mà bạn có thể đọc thêm về Wikipedia . 11 hữu ích 0 bình luận chia sẻ answer 6 Đây có thể không phải là giải pháp tốt nhất tuy nhiên đây là cách tôi đã làm. import string f =lambda x:''.join[[i for i in x if i notin string.punctuation]] 6 hữu ích 0 bình luận chia sẻ answer 6 Đây là một chức năng tôi đã viết. Nó không hiệu quả lắm, nhưng nó đơn giản và bạn có thể thêm hoặc xóa bất kỳ dấu câu nào bạn muốn: def 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 6 hữu ích 0 bình luận chia sẻ answer 6 Đây là một lớp lót cho Python 3.5: import string "l*ots! o[f. p@u]n[c}t]u[a'ti\"on#$^?/".translate[str.maketrans[{a:Nonefor a in string.punctuation}]] 6 hữu ích 0 bình luận chia sẻ answer 6 Tôi chưa thấy câu trả lời này. Chỉ cần sử dụng một regex; nó loại bỏ tất cả các ký tự bên cạnh các ký tự từ [ \w] và ký tự số [ \d], theo sau là ký tự khoảng trắng [ \s]: import re s ="string. With. Punctuation?"# Sample string out = re.sub[ur'[^\w\d\s]+','', s] 6 hữu ích 3 bình luận chia sẻ answer 4 Đây là một giải pháp không có regex. import 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 andor then
4 hữu ích 0 bình luận chia sẻ answer 4 Cũng giống như một bản cập nhật, tôi viết lại ví dụ @Brian trong Python 3 và thực hiện các thay đổi cho nó để di chuyển bước biên dịch regex bên trong hàm. Tôi nghĩ ở đây là thời gian từng bước cần thiết để làm cho chức năng hoạt động. Có lẽ bạn đang sử dụng điện toán phân tán và không thể có đối tượng regex được chia sẻ giữa các công nhân của bạn và cần phải có re.compiletừng bước tại mỗi công nhân. Ngoài ra, tôi đã tò mò về thời gian hai cách triển khai maketrans khác nhau cho Python 3 table = str.maketrans[{key:Nonefor key in string.punctuation}] đấu với table = str.maketrans['','', string.punctuation] Thêm vào đó tôi đã thêm một phương thức khác để sử dụng tập hợp, trong đó tôi tận dụng hàm giao nhau để giảm số lần lặp. Đây là mã hoàn chỉnh: import re, string, timeit s ="string. With. Punctuation"def test_set[s]: exclude = set[string.punctuation]return''.join[ch for ch in s if ch notin 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:Nonefor 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 solutionfor 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]] Đây là kết quả của tôi: sets :3.1830138750374317 sets2 :2.189873124472797 regex :7.142953420989215 translate :4.243278483860195 translate2 :2.427158243022859 replace :4.579746678471565 4 hữu ích 0 bình luận chia sẻ answer 3 >>> s ="string. With. Punctuation?">>> s = re.sub[r'[^\w\s]','',s]>>> re.split[r'\s*', s] ['string','With','Punctuation'] 3 hữu ích 1 bình luận chia sẻ answer 3 import re s ="string. With. Punctuation?"# Sample string out = re.sub[r'[^a-zA-Z0-9\s]','', s] 3 hữu ích 0 bình luận chia sẻ answer 2 Một lớp lót có thể hữu ích trong các trường hợp không nghiêm ngặt: ''.join[[c for c in s if c.isalnum[]or c.isspace[]]] 2 hữu ích 0 bình luận chia sẻ answer 1 Tìm kiếm và thay thế bằng cách sử dụng các hàm regex, như được thấy ở đây. . Nếu bạn phải liên tục thực hiện thao tác, bạn có thể giữ một bản sao được biên dịch của mẫu biểu thức chính quy [dấu chấm câu của bạn] xung quanh, điều này sẽ tăng tốc mọi thứ lên một chút. 1 hữu ích 3 bình luận chia sẻ answer 1 #FIRST METHOD #Storing all punctuations in a variable punctuation='!?,.:;"\'][_-' newstring=''#Creating empty string word=raw_input["Enter string: "]for i in word:if[i notin 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 methodsEnter string: hello! welcome -to_python[programming.language]??,The string without punctuation is: hello welcome topythonprogramminglanguage 1 hữu ích 0 bình luận chia sẻ answer 1 with 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='\n']print["____________"] 1 hữu ích 0 bình luận chia sẻ answer 1 Xóa các từ dừng khỏi tệp văn bản bằng Python print['====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 notin stop_words:print ["____________"]print[i,end='\n'] 1 hữu ích 0 bình luận chia sẻ answer 1 Đây là cách thay đổi tài liệu của chúng tôi thành chữ hoa hoặc chữ thường. print['@@@@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 hữu ích 0 bình luận chia sẻ |