2016-10-09 6 views
1

Pythonでは、リストからほとんどすべての句読点を削除する必要がありますが、ピリオドとコンマは保存してください。これまたは変数を実行する関数を作成する必要がありますか?基本的には、文字を除くすべての記号(私はすでに大文字を小文字に変換しています)とピリオドとコンマ(そしておそらくアポストロフィ)を削除したいと思います。ピリオド、コンマ以外のPythonリストから句読点/記号を削除する

#Clean tokens up (remove symbols except ',' and '.') 

def depunctuate() 
    clean_tokens = [] 

    for i in lc_tokens: 
     if (i not in [a-z.,]) 
     ... 

答えて

0
import string 

# Create a set of all allowed characters. 
# {...} is the syntax for a set literal in Python. 
allowed = {",", "."}.union(string.ascii_lowercase) 

# This is our starting string. 
lc_tokens = 'hello, "world!"' 

# Now we use list comprehension to only allow letters in our allowed set. 
# The result of list comprehension is a list, so we use "".join(...) to 
# turn it back into a string. 
filtered = "".join([letter for letter in lc_tokens if letter in allowed]) 

# Our final result has everything but lowercase letters, commas, and 
# periods removed. 
assert filtered == "hello,world" 
+0

これは望ましくない(句読点)記号だけでなく、空白文字と非ASCII文字を取り除くだけでなく、 "naive"のような単語を "nave"に変換します。 – lenz

+0

はい、ASCII小文字といくつかの句読点文字のみを使用できます。これが要件の解釈ですが、質問者が「手紙」という言葉を使用するときの意味に大きく依存しています。もう1つの答えにも同様の問題があります。それは 'string.punctuation'の中のものを削除しますが、元の質問者が削除したいと思っている全ての"記号 "を覆うかどうかは不明です。 – smarx

+0

あなたは正しいです、 'string.punctuation'にはたくさんの句読記号もありません。素晴らしい引用符。それでも、私は "文字"と "句読記号"はかなり明確なカテゴリであると思います(そして、実際にはUnicodeの文字プロパティを調べるのはかなり簡単です)。 – lenz

2

あなたはstring.punctuationから不要な句読点のセットを構築することができます - 句読点を含む文字列を提供し、その後、セットに含まれる文字をフィルタリングするためにリスト内包を使用します。

import string 

to_delete = set(string.punctuation) - {'.', ','} # remove comma and fullstop 
clean_tokens = [x for x in lc_tokens if x not in to_delete] 
+0

ありがとうございます。 ^^ –

関連する問題