次の方法よりも簡単な方法があるはずです。
import string
s = "string. With. Punctuation?" # Sample string
out = s.translate(string.maketrans("",""), string.punctuation)
ある?
次の方法よりも簡単な方法があるはずです。
import string
s = "string. With. Punctuation?" # Sample string
out = s.translate(string.maketrans("",""), string.punctuation)
ある?
効率の観点からは、他社に勝るものはありません
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
正規表現は、知っていれば十分に単純です。
import re
s = "string. With. Punctuation?"
s = re.sub(r'[^\w\s]','',s)
使いやすいように、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
myString.translate(None, string.punctuation)
私は通常次のようなものを使用します:
>>> s = "string. With. Punctuation?" # Sample string
>>> import string
>>> for c in string.punctuation:
... s= s.replace(c,"")
...
>>> s
'string With Punctuation'
reファミリーに精通している場合は、必ずしも単純ではありませんが、別の方法です。
import re, string
s = "string. With. Punctuation?" # Sample string
out = re.sub('[%s]' % re.escape(string.punctuation), '', s)
string.punctuation
ASCIIのみです!より正確な (ただし、はるかに遅い) 方法は、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')
また~*+§$
、視点に応じて「句読点」である場合とそうでない場合があるような文字を削除します。
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'))
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 で文字列から句読点を削除する最良の方法だと思います。理由は次のとおりです。
\{S}
句読点を削除したい場合は を削除できますが、 などの記号はそのままにしておきます$
。\{Pd}
ダッシュのみを削除します。これは、ウィキペディアで詳細を読むことができるUnicode 文字プロパティを使用します。
この答えはまだ見ていません。正規表現を使用するだけです。\w
単語文字 ( ) と数字文字 ( )以外のすべての文字を削除し\d
、その後に空白文字 ( \s
)が続きます。
import re
s = "string. With. Punctuation?" # Sample string
out = re.sub(ur'[^\w\d\s]+', '', s)
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}))
これは最善の解決策ではないかもしれませんが、これが私のやり方です。
import string
f = lambda x: ''.join([i for i in x if i not in string.punctuation])
ここに私が書いた関数があります。あまり効率的ではありませんが、シンプルで、必要に応じて句読点を追加または削除できます。
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
>>> s = "string. With. Punctuation?"
>>> s = re.sub(r'[^\w\s]','',s)
>>> re.split(r'\s*', s)
['string', 'With', 'Punctuation']
あまり厳密ではない場合には、ワンライナーが役立つ場合があります。
''.join([c for c in s if c.isalnum() or c.isspace()])
正規表現を使用しないソリューションを次に示します。
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
# 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
Unicode 文字列を扱うときは、Unicode プロパティ クラス ( /など) と POSIX 文字クラス ( など) の両方をサポートするPyPiregex
モジュールを使用することをお勧めします。\p{X}
\P{X}
[:name:]
pip install regex
ターミナルで(または) と入力してパッケージをインストールし、pip3 install regex
ENTER キーを押します。
句読点やあらゆる種類の記号 (つまり、文字、数字、空白以外のもの) を削除する必要がある場合は、次を使用できます。
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
パターンを追加しました
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')