4

文字列から URL を削除し、元のコンテンツのタイトルに置き換えたいと思います。

例えば:

mystring = "Ah I like this site: http://www.stackoverflow.com. Also I must say I like http://www.digg.com"

sanitize(mystring) # it becomes "Ah I like this site: Stack Overflow. Also I must say I like Digg - The Latest News Headlines, Videos and Images"

URL をタイトルに置き換えるために、次のスニペットを作成しました。

#get_title: string -> string
def get_title(url):
    """Returns the title of the input URL"""

    output = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))
    return output.title.string

この関数を文字列に適用して、URL をキャッチし、get_title を介してタイトルに変換する必要があります。

4

2 に答える 2

3

Python で URL を検証するための情報を含む質問があります: Pythonで正規表現を使用して URL を検証するにはどうすればよいですか?

urlparseモジュールがおそらく最善の策です。アプリケーションのコンテキストで有効な URL を構成するものを決定する必要があります。

URL の文字列を確認するには、文字列内の各単語を反復処理して確認し、有効な URL をタイトルに置き換えます。

コード例 (valid_url を記述する必要があります):

def sanitize(mystring):
  for word in mystring.split(" "):
    if valid_url(word):
      mystring = mystring.replace(word, get_title(word))
  return mystring
于 2010-05-08T18:26:25.823 に答える
2

おそらく正規表現と置換を使用してこれを解決できます (re.sub は関数を受け入れ、出現ごとに Match オブジェクトが渡され、それを置き換える文字列を返します)。

url = re.compile("http:\/\/(.*?)/")
text = url.sub(get_title, text)

難しいのは、URL に一致する正規表現を作成することです。

于 2010-05-08T17:37:20.403 に答える