2016-12-03 9 views
2

で終わり、私は、以下の説明に従って関数を作成する必要があります。Python - テキストからハッシュタグを抽出する。私のプログラミングクラスの句読点

パラメータがつぶやきです。この関数は、ツイートのハッシュタグをすべて含むリストを、ツイートに表示されている順序で返します。返されるリストの各ハッシュタグは、最初のハッシュ記号が削除され、ハッシュタグは一意でなければなりません。 (ハットタグが同じハッシュタグを2回使用している場合、ハッシュタグの順序は、そのツイートの最初のタグの順序と一致する必要があります)。

わかりません句読点に遭遇するとハッシュタグが終了するようにします(2番目のdoctestの例を参照)。現在のコードで何も出力されていません:

def extract(start, tweet): 
    """ (str, str) -> list of str 

    Return a list of strings containing all words that start with a specified character. 

    >>> extract('@', "Make America Great Again, vote @RealDonaldTrump") 
    ['RealDonaldTrump'] 
    >>> extract('#', "Vote Hillary! #ImWithHer #TrumpsNotMyPresident") 
    ['ImWithHer', 'TrumpsNotMyPresident'] 
    """ 

    words = tweet.split() 
    return [word[1:] for word in words if word[0] == start] 

def strip_punctuation(s): 
    """ (str) -> str 

    Return a string, stripped of its punctuation. 

    >>> strip_punctuation("Trump's in the lead... damn!") 
    'Trumps in the lead damn' 
    """ 
    return ''.join(c for c in s if c not in '!"#$%&\'()*+,-./:;<=>[email protected][\\]^_`{|}~') 

def extract_hashtags(tweet): 
    """ (str) -> list of str 

    Return a list of strings containing all unique hashtags in a tweet. 
    Outputted in order of appearance. 

    >>> extract_hashtags("I stand with Trump! #MakeAmericaGreatAgain #MAGA #TrumpTrain") 
    ['MakeAmericaGreatAgain', 'MAGA', 'TrumpTrain'] 
    >>> extract_hashtags('NEVER TRUMP. I'm with HER. Does #this! work?') 
    ['this'] 
    """ 

    hashtags = extract('#', tweet) 

    no_duplicates = [] 

    for item in hashtags: 
     if item not in no_duplicates and item.isalnum(): 
      no_duplicates.append(item) 

    result = [] 
    for hash in no_duplicates: 
     for char in hash: 
      if char.isalnum() == False and char != '#': 
       hash == hash[:char.index()] 
       result.append() 
    return result 

私はこの時点でかなり失われています。どんな助けもありがとう。前もって感謝します。

注:ではありません。正規表現の使用やモジュールのインポートが許可されていません。

+1

まあ、あなたが句読点で終わらなければならない場合、*その*句読記号がたくさんない場合、次の文字が句読点であるかどうかチェックしてみませんか? – Pythonista

答えて

0

少し失われています。この種の問題を解決する鍵は、問題をより小さな部分に分割し、問題を解決してから結果を結合することです。あなたは..あなたが必要とするすべての部分を持っている:

def extract_hashtags(tweet): 
    # strip the punctuation on the tags you've extracted (directly) 
    hashtags = [strip_punctuation(tag) for tag in extract('#', tweet)] 
    # hashtags is now a list of hash-tags without any punctuation, but possibly with duplicates 

    result = [] 
    for tag in hashtags: 
     if tag not in result: # check that we haven't seen the tag already (we know it doesn't contain punctuation at this point) 
      result.append(tag) 
    return result 

PS:これは正規表現のソリューションに適しています問題ですが、あなたは高速strip_punctuationをしたい場合は、使用できます。

def strip_punctuation(s): 
    return s.translate(None, '!"#$%&\'()*+,-./:;<=>[email protected][\\]^_`{|}~') 
関連する問題