2013-11-25 35 views
-1

我已經使用json從web讀取twitter數據,所以它是字典形式。我必須使用Python找到TweetID以300或700結尾的推文。我知道我必須使用正則表達式,但我不熟練使用正則表達式。任何人都可以幫忙嗎?使用正則表達式在Python中查找值

import re 
with open("tweet37.txt", "w") as o: 
    for tweet in tweets: 
     tweet_id = tweet['id'] 
     if tweet_id == re.compile(r'd*700' or 'd*300'): 
      print >> o, str(tweet['id']) 

這沒有給出任何錯誤,但沒有匹配任何ID。輸出文件是空白的。

這就是ID的樣子。他們在微博中Tweet字典[ '身份證']

400051062968557600 
400051063002116100 
400051062985330700 

回答

1

str方法也可以工作。

with open("tweet37.txt", "w") as o: 
    for tweet in tweets: 
     tweet_id = tweet['id'] 
     if tweet_id.endswith('700') or tweet_id.endswith('300'): 
      print >> o, str(tweet['id']) 
+0

謝謝,它的工作。 –

1

兩件事情:

  1. 你拼寫爲 「編譯」 錯誤。
  2. 您的正則表達式模式無效。

這是你的正則表達式應該是什麼樣子:

if re.search('(?:300|700)$', tweet_id): 

(?:300|700)比賽無論是300700,並在字符串的結尾$匹配。

+0

謝謝修復了錯字。我運行了代碼,但它不匹配任何ID。輸出文件是空白的。 –