0

最長の繰り返しパターンから文字列を削除する方法を探しています。

私は約1000のWebページのタイトルのリストを持っていますが、それらはすべて、Webサイトの名前である共通のサフィックスを共有しています。

彼らはこのパターンに従います:

['art gallery - museum and visits | expand knowledge',
 'lasergame - entertainment | expand knowledge',
 'coffee shop - confort and food | expand knowledge',
 ...
]

共通のサフィックスからすべての文字列を自動的に削除するにはどうすればよい" | expand knowledge" ですか?

ありがとう!

編集:申し訳ありませんが、私は自分自身を十分に明確にしませんでした。接尾辞についての情報" | expand knowledge"は事前にありません。共通のサフィックスの可能性がある文字列のリストを、それが何であるかわからなくてもクリアできるようにしたい。

4

3 に答える 3

4

os.path.commonprefix反転したタイトルの関数を使用した解決策は次のとおりです。

titles = ['art gallery - museum and visits | expand knowledge',
 'lasergame - entertainment | expand knowledge',
 'coffee shop - confort and food | expand knowledge',
]

# Find the longest common suffix by reversing the strings and using a 
# library function to find the common "prefix".
common_suffix = os.path.commonprefix([title[::-1] for title in titles])[::-1]

# Strips all titles from the number of characters in the common suffix.
stripped_titles = [title[:-len(common_suffix)] for title in titles]

結果:

['アートギャラリー-美術館と訪問'、'レーザーゲーム-エンターテインメント'、'コーヒーショップ-快適さと食べ物']

共通の接尾辞がそれ自体で検出されるため、接尾辞がわからない場合でも、タイトルの任意のグループで機能するはずです。

于 2012-11-19T20:28:35.483 に答える
1

削除するサフィックスが実際にわかっている場合は、次のようにするだけです。

suffix = " | expand knowledge"

your_list = ['art gallery - museum and visits | expand knowledge',
 'lasergame - entertainment | expand knowledge',
 'coffee shop - confort and food | expand knowledge',
...]

new_list = [name.rstrip(suffix) for name in your_list]
于 2012-11-19T20:27:03.540 に答える
0

すべての文字列に共通のサフィックスがあることが確実な場合は、これでうまくいきます。

strings = [
  'art gallery - museum and visits | expand knowledge',
  'lasergame - entertainment | expand knowledge']
suffixlen = len(" | expand knowledge")
print [s[:-suffixlen] for s in strings]    

出力:

['art gallery - museum and visits', 'lasergame - entertainment']
于 2012-11-19T20:25:22.263 に答える