777

次の方法よりも簡単な方法があるはずです。

import string
s = "string. With. Punctuation?" # Sample string 
out = s.translate(string.maketrans("",""), string.punctuation)

ある?

4

31 に答える 31

1182

効率の観点からは、他社に勝るものはありません

s.translate(None, string.punctuation)

Python の上位バージョンでは、次のコードを使用します。

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

ルックアップ テーブルを使用して C で生の文字列操作を実行しています。これに勝るものはあまりなく、独自の C コードを記述します。

速度が心配でない場合は、別のオプションがあります。

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

これは各文字で s.replace よりも高速ですが、以下のタイミングからわかるように、正規表現や string.translate などの非純粋な python アプローチほどには機能しません。この種の問題では、できるだけ低いレベルで行うことが効果的です。

タイミングコード:

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 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)

これにより、次の結果が得られます。

sets      : 19.8566138744
regex     : 6.86155414581
translate : 2.12455511093
replace   : 28.4436721802
于 2008-11-05T18:36:11.530 に答える
186

正規表現は、知っていれば十分に単純です。

import re
s = "string. With. Punctuation?"
s = re.sub(r'[^\w\s]','',s)
于 2013-05-28T18:47:47.263 に答える
86

使いやすいように、Python 2 と Python 3 の両方で文字列から句読点を削除するというメモをまとめます。詳細な説明については、他の回答を参照してください。


パイソン 2

import string

s = "string. With. Punctuation?"
table = string.maketrans("","")
new_s = s.translate(table, string.punctuation)      # Output: string without punctuation

パイソン3

import string

s = "string. With. Punctuation?"
table = str.maketrans(dict.fromkeys(string.punctuation))  # OR {key: None for key in string.punctuation}
new_s = s.translate(table)                          # Output: string without punctuation
于 2016-05-14T01:57:29.917 に答える
52
myString.translate(None, string.punctuation)
于 2010-03-08T15:19:09.570 に答える
33

私は通常次のようなものを使用します:

>>> s = "string. With. Punctuation?" # Sample string
>>> import string
>>> for c in string.punctuation:
...     s= s.replace(c,"")
...
>>> s
'string With Punctuation'
于 2008-11-05T17:41:27.210 に答える
31

reファミリーに精通している場合は、必ずしも単純ではありませんが、別の方法です。

import re, string
s = "string. With. Punctuation?" # Sample string 
out = re.sub('[%s]' % re.escape(string.punctuation), '', s)
于 2008-11-05T17:39:55.467 に答える
30

string.punctuationASCIIのみです!より正確な (ただし、はるかに遅い) 方法は、unicodedata モジュールを使用することです。

# -*- 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

他のタイプの文字も一般化して削除できます。

''.join(ch for ch in s if category(ch)[0] not in 'SP')

また~*+§$、視点に応じて「句読点」である場合とそうでない場合があるような文字を削除します。

于 2011-09-01T09:29:45.957 に答える
16

Python 3strまたは Python 2のunicode値の場合、str.translate()辞書のみを取ります。コードポイント (整数) はそのマッピングで検索され、マップされたものNoneはすべて削除されます。

次に、句読点(一部?)を削除するには、次を使用します。

import string

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

dict.fromkeys()クラス メソッドにより、マッピングの作成が簡単になりNone、キーのシーケンスに基づいてすべての値が設定されます。

ASCII 句読点だけでなく、すべての句読点を削除するには、テーブルを少し大きくする必要があります。JF Sebastian の回答(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'))
于 2013-09-02T09:57:54.767 に答える
14

string.punctuation現実の世界で一般的に使用される多くの句読点を見逃しています。非 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()

個人的には、これが Python で文字列から句読点を削除する最良の方法だと思います。理由は次のとおりです。

  • すべての Unicode 句読点を削除します
  • 簡単に変更できます。たとえば、\{S}句読点を削除したい場合は を削除できますが、 などの記号はそのままにしておきます$
  • 保持したいものと削除したいものを具体的に把握できます。たとえば、\{Pd}ダッシュのみを削除します。
  • この正規表現は空白も正規化します。タブ、キャリッジ リターン、およびその他の奇妙な要素を適切な 1 つのスペースにマップします。

これは、ウィキペディアで詳細を読むことができるUnicode 文字プロパティを使用します。

于 2016-10-06T16:46:01.707 に答える
11

この答えはまだ見ていません。正規表現を使用するだけです。\w単語文字 ( ) と数字文字 ( )以外のすべての文字を削除し\d、その後に空白文字 ( \s)が続きます。

import re
s = "string. With. Punctuation?" # Sample string 
out = re.sub(ur'[^\w\d\s]+', '', s)
于 2016-06-18T06:38:57.390 に答える
10

Python 3.5 のワンライナーは次のとおりです。

import string
"l*ots! o(f. p@u)n[c}t]u[a'ti\"on#$^?/".translate(str.maketrans({a:None for a in string.punctuation}))
于 2016-03-21T02:46:47.040 に答える
9

これは最善の解決策ではないかもしれませんが、これが私のやり方です。

import string
f = lambda x: ''.join([i for i in x if i not in string.punctuation])
于 2011-07-05T04:30:07.097 に答える
7

ここに私が書いた関数があります。あまり効率的ではありませんが、シンプルで、必要に応じて句読点を追加または削除できます。

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
于 2015-09-22T14:30:47.140 に答える
5
>>> s = "string. With. Punctuation?"
>>> s = re.sub(r'[^\w\s]','',s)
>>> re.split(r'\s*', s)


['string', 'With', 'Punctuation']
于 2016-08-24T05:43:58.777 に答える
5

あまり厳密ではない場合には、ワンライナーが役立つ場合があります。

''.join([c for c in s if c.isalnum() or c.isspace()])
于 2015-10-17T23:03:59.523 に答える
5

正規表現を使用しないソリューションを次に示します。

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 and or then
  • 句読点をスペースに置き換えます
  • 単語間の複数のスペースを 1 つのスペースに置き換える
  • 末尾のスペースがある場合は、strip() で削除します
于 2016-11-30T10:29:40.070 に答える
4
# 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
于 2017-01-02T08:56:57.190 に答える
0

Unicode 文字列を扱うときは、Unicode プロパティ クラス ( /など) と POSIX 文字クラス ( など) の両方をサポートするPyPiregexモジュールを使用することをお勧めします。\p{X}\P{X}[:name:]

pip install regexターミナルで(または) と入力してパッケージをインストールし、pip3 install regexENTER キーを押します。

句読点やあらゆる種類の記号 (つまり、文字、数字、空白以外のもの) を削除する必要がある場合は、次を使用できます。

regex.sub(r'[\p{P}\p{S}]', '', text)  # to remove one by one
regex.sub(r'[\p{P}\p{S}]+', '', text) # to remove all consecutive punctuation/symbols with one go
regex.sub(r'[[:punct:]]+', '', text)  # Same with a POSIX character class

オンラインの Python デモを参照してください。

import regex

text = 'भारत India <><>^$.,,! 002'
new_text = regex.sub(r'[\p{P}\p{S}\s]+', ' ', text).lower().strip()
# OR
# new_text = regex.sub(r'[[:punct:]\s]+', ' ', text).lower().strip()

print(new_text)
# => भारत india 002

ここでは、文字クラスに空白\sパターンを追加しました

于 2021-12-01T14:37:52.480 に答える
-1

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 not in stop_words:

            print ("____________")

            print(i,end='\n')
于 2017-01-05T08:00:04.467 に答える