文字列から句読点を削除するPythonプログラム

Python

文を単語のリストに分割したい場合があります。

このような場合、最初に文字列をクリーンアップして、すべての句読点を削除することをお勧めします。 これがどのように行われるかの例です。

ソースコード

# define punctuation
punctuations = '''!()-[]{};:'",<>./?@#$%^&*_~'''

my_str = "Hello!!!, he said ---and went."

# To take input from the user
# my_str = input("Enter a string: ")

# remove punctuation from the string
no_punct = ""
for char in my_str:
   if char not in punctuations:
       no_punct = no_punct + char

# display the unpunctuated string
print(no_punct)

出力

Hello he said and went

このプログラムでは、最初に句読点の文字列を定義します。 次に、提供された文字列を次のように繰り返します。 for ループ。

各反復で、メンバーシップテストを使用して、文字が句読点であるかどうかを確認します。 句読点でない場合は、文字を追加(連結)する空の文字列があります。 最後に、クリーンアップされた文字列を表示します。



Hope this helps!

Source link

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です