1

不要な文字を削除したい Python 文字列がいくつかあります。

例:

"This is '-' a test" 
     should be "This is a test"
"This is a test L)[_U_O-Y OH : l’J1.l'}/"
     should be "This is a test"
"> FOO < BAR" 
     should be "FOO BAR"
"I<<W5§!‘1“¢!°\" I" 
     should be "" 
     (because if only words are extracted then it returns I W I and none of them form words)
"l‘?£§l%nbia  ;‘\\~siI.ve_rswinq m"
     should be ""
"2|'J]B"
     should be ""

これは私がこれまでに持っているものですが、単語間の元のスペースを保持していません。

>>> line = re.sub(r"\W+","","This is '-' a test")
>>> line
'Thisisatest'
>>> line = re.sub(r"\W+","","This is a test L)[_U_O-Y OH : l’J1.l'}/")
>>> line
'ThisisatestL_U_OYOHlJ1l' 
#although i would prefer this to be "This is a test" but if not possible i would 
 prefer "This is a test L_U_OYOHlJ1l"
>>> line = re.sub(r"\W+","","> FOO < BAR")
>>> line
'FOOBAR'
>>> line = re.sub(r"\W+","","I<<W5§!‘1“¢!°\" I")
>>> line
'IW51I'
>>> line = re.sub(r"\W+","","l‘?£§l%nbia  ;‘\\~siI.ve_rswinq m")  
>>> line
'llnbiasiIve_rswinqm'
>>> line = re.sub(r"\W+","","2|'J]B")
>>> line
'2JB'

後で定義済みの単語のリストを使用して、正規表現でクリーンアップされた単語をフィルタリングします。

4

2 に答える 2

0

これは、少なくとも 1 つの非アルファベット文字を含む非スペース記号のグループをクリアします。ただし、不要な文字グループがいくつか残ります。

re.sub(r"\w*[^a-zA-Z ]+\w*","","This is a test L)[_U_O-Y OH : l’J1.l'}/")

与える:

'This is a test  OH  '

また、複数のスペースのグループを残します:

re.sub(r"[^a-zA-Z ]+\w*","","This is '-' a test")
'This is  a test'  # two spaces
于 2013-10-13T17:35:56.460 に答える
0

次のように、分割とフィルターを使用します。

' '.join(word for word in line.split() if word.isalpha() and word.lower() in list)

これにより、リストにないアルファベット以外の単語とアルファベットの単語がすべて削除されます。

例:

def myfilter(string):
    words = {'this', 'test', 'i', 'a', 'foo', 'bar'}
    return ' '.join(word for word in line.split() if word.isalpha() and word.lower() in words)

>>> myfilter("This is '-' a test")
'This a test'
>>> myfilter("This is a test L)[_U_O-Y OH : l’J1.l'}/")
'This a test'
>>> myfilter("> FOO < BAR")
'FOO BAR'
>>> myfilter("I<<W5§!‘1“¢!°\" I")
'I'
>>> myfilter("l‘?£§l%nbia  ;‘\\~siI.ve_rswinq m")
''
>>> myfilter("2|'J]B")
''
于 2013-10-13T17:31:13.857 に答える