2016-11-28 3 views
0

私は短い文字列(つぶやき)を持っています。そこでは、テキストからすべての言い回しを抽出し、繰り返しを含むこれらのインスタンスのリストを返す必要があります。句読点/空白スペースの最初のインスタンスの後にすべての文字を削除するにはどうすればよいですか?

extract_mentions(」。@ AndreaTantaros-supersleuth!あなたは真のジャーナリズムのプロです。偉大な仕事を続けて!#MakeAmericaGreatAgain') [AndreaTantaros]

「@」の後の最初の句読点の後にすべてのテキストを削除するにはどうすればよいですか? (この場合は「 - 」となります)注意、句読点は変更することができます。正規表現は使用しないでください。これはのみだけで一致し、テキストの一部を抽出するために正規表現を使用して1つの余分な文字

+0

それでは、あなたが試行しましたが、あなたが期待通りになぜそれが動作しませんか? –

答えて

-1

とインスタンスのために働くだろう

tweet_list = tweet.split() 
    mention_list = [] 
    for word in tweet_list: 
     if '@' in word: 
      x = word.index('@') 
      y = word[x+1:len(word)] 
      if y.isalnum() == False: 
       y = word[x+1:-1] 
       mention_list.append(y) 
      else:     
       mention_list.append(y) 
    return mention_list 

私は次のように使用しています。

+0

OPから:*正規表現を使用しないでください。* –

+0

申し訳ありません。それを読まなかった。とにかく、正規表現はこの作業のために最も速く全体的に適切な方法です。 – socketpair

0

string.punctuationモジュールを使用して、すべての句読文字を取得します。

句読点の間に最初の文字を削除します(そうでない場合、答えは常に空の文字列になります)。次に、最初の句読点を見つけます。

これは、反対の条件の2つのループと、より良い速度のためにsetを使用します。

z ="[email protected]! You are a true journalistic professional. Keep up the great work! #MakeAmericaGreatAgain') [AndreaTantaros]" 

import string 

# skip leading punctuation: find position of first non-punctuation 

spun=set(string.punctuation) # faster if searched from a set 

start_pos = 0 
while z[start_pos] in spun: 
    start_pos+=1 

end_pos = start_pos 
while z[end_pos] not in spun: 
    end_pos+=1 

print(z[start_pos:end_pos]) 
0
import string 

def extract_mentions(s, delimeters = string.punctuation + string.whitespace): 
    mentions = [] 
    begin = s.find('@') 
    while begin >= 0: 
    end = begin + 1 
    while end < len(s) and s[end] not in delimeters: 
     end += 1 
    mentions.append(s[begin+1:end]) 
    begin = s.find('@', end) 
    return mentions 


>>> print(extract_mentions('[email protected]! You are a true journalistic professional. Keep up the great work! #MakeAmericaGreatAgain')) 
['AndreaTantaros'] 
関連する問題